Talentd
FleetCode
Make and follow sheets.Sign in

Determine the Minimum Sum of a k-avoiding Array solution and explanation

MediumGreedyMath5 min read59.7% acceptanceUpdated 9 Apr 2026
Leetcode Weekly contest 359 - Medium- Determine the Minimum Sum of a k-avoiding ArrayPrakhar Agrawal · 4:31 · 603 viewsWatch on YouTube
9 more videos on this problem
  1. Leetcode Weekly contest 359 - Medium- Determine the Minimum Sum of a k-avoiding ArrayPrakhar Agrawal · 4:31 · 603 views
  2. Leetcode 2829 Determine the Minimum Sum of a k avoiding ArrayThinkCode · 5:56 · 565 views
  3. 2829. Determine the Minimum Sum of a k-avoiding Array (Leetcode Medium)Programming Live with Larry · 8:57 · 363 views
  4. Determine the Minimum Sum of a k-avoiding Array | Leetcode 2829 | Contest 359Tech Courses · 6:09 · 331 views
  5. determine the minimum sum of a k - avoiding array #leetcodechallenge #leetcodecrazy developers · 0:33 · 258 views
  6. 28 Determine the Minimum Sum of a k avoiding Array LeetCode Contest Google Chrome 2023 08 20 08Cygnatrix · 0:41 · 230 views
  7. Leetcode 2829 Determine the Minimum Sum of a k-avoiding ArrayTech Diet · 3:38 · 94 views
  8. Determine the Minimum Sum of a k-avoiding Array | Weekly Contest 359 |Leetcode 2829 | MediumLet's Code Together · 3:23 · 93 views
  9. [Weekly Contest 359] 2829. Determine the Minimum Sum of a k avoiding Array (Python 中文解說)陳逸星 · 6:17 · 13 views
  10. Weekly Contest 359 ||Check if String Is Acronym of Words || Minimum Sum of a k-avoiding ArrayAshX Coder · 8:28 · 44 views

The problem

You are given two integers, n and k.

An array of distinct positive integers is called a k-avoiding array if there does not exist any pair of distinct elements that sum to k.

Return the minimum possible sum of a k-avoiding array of length n.

Example 1:

Input: n = 5, k = 4
Output: 18
Explanation: Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.

Example 2:

Input: n = 2, k = 6
Output: 3
Explanation: We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.

Constraints:

  • 1 <= n, k <= 50

Approach overview

Problem Overview: You need to build an array of n positive integers such that no two elements add up to k. Among all valid arrays, return the minimum possible sum of its elements.

Approach 1: Incremental Element Selection (Greedy with Set) (Time: O(n), Space: O(n))

Build the array one number at a time starting from 1. For every candidate number x, check whether its complement k - x already exists in the chosen set. If it does, adding x would create a pair whose sum equals k, so skip it. Otherwise include x and continue until you collect n numbers.

This works because choosing the smallest valid numbers always minimizes the total sum. A hash set allows constant‑time complement checks while iterating through natural numbers. The algorithm performs at most a few extra skips, so it remains linear in practice. This approach directly models the greedy rule and is easy to reason about during interviews involving greedy decisions and simple math observations.

Approach 2: Direct Number Generation (Math + Greedy Insight) (Time: O(n), Space: O(1))

Observe the structure of forbidden pairs: x conflicts with k - x. To minimize the sum, you want the smallest possible integers. All numbers from 1 up to k / 2 can safely be chosen because their complements lie in the larger range near k. After selecting those values, the next safe numbers must start from k, since any number between k/2 and k-1 would pair with something already chosen.

So the construction becomes deterministic: first take numbers from 1 upward until reaching k/2 (or until the array already has n elements). If more elements are needed, continue from k, k+1, and so on. This avoids complement conflicts entirely and removes the need for a hash set. The result is a clean arithmetic construction based purely on math reasoning.

Recommended for interviews: The incremental greedy approach demonstrates clear understanding of the constraint by explicitly checking complements. Interviewers often accept it first because it is intuitive and easy to verify. The direct generation method shows deeper pattern recognition and stronger greedy reasoning, making it the most polished final solution.

Approach 1: Approach with Incremental Element Selection

This approach selects the smallest natural numbers step by step until the desired length n is achieved ensuring no pair sums to k. If a number would create a pair summing to k with a number already in the array, it is skipped.

def min_k_avoiding_sum(n, k):
    sum_total, count, current = 0, 0, 1
    while count < n:
        complement = k - current
        if current < complement:
            sum_total += current
            count += 1
        current += 1
    return sum_total

n, k = 5, 4
print(min_k_avoiding_sum(n, k))
public class KAvoidingSum {
    public static int minKAvoidingSum(int n, int k) {
        int sum = 0, count = 0, current = 1;
        while (count < n) {
            int complement = k - current;
            if (current < complement) {
                sum += current;
                count++;
            }
            current++;
        }
        return sum;
    }

    public static void main(String[] args) {
        int n = 5, k = 4;
        System.out.println(minKAvoidingSum(n, k));
    }
}
#include <iostream>

int min_k_avoiding_sum(int n, int k) {
    int sum = 0, count = 0, current = 1;
    while (count < n) {
        int complement = k - current;
        if (current < complement) {
            sum += current;
            count++;
        }
        current++;
    }
    return sum;
}

int main() {
    int n = 5, k = 4;
    std::cout << min_k_avoiding_sum(n, k) << std::endl;
    return 0;
}
function minKAvoidingSum(n, k) {
    let sum = 0, count = 0, current = 1;
    while (count < n) {
        let complement = k - current;
        if (current < complement) {
            sum += current;
            count++;
        }
        current++;
    }
    return sum;
}

let n = 5, k = 4;
console.log(minKAvoidingSum(n, k));
#include <stdio.h>

int min_k_avoiding_sum(int n, int k) {
    int sum = 0, count = 0, current = 1;
    while (count < n) {
        int complement = k - current;
        if (current < complement) {
            sum += current;
            count++;
        }
        current++;
    }
    return sum;
}

int main() {
    int n = 5, k = 4;
    printf("%d\n", min_k_avoiding_sum(n, k));
    return 0;
}
using System;

public class KAvoidingSum {
    public static int MinKAvoidingSum(int n, int k) {
        int sum = 0, count = 0, current = 1;
        while (count < n) {
            int complement = k - current;
            if (current < complement) {
                sum += current;
                count++;
            }
            current++;
        }
        return sum;
    }

    public static void Main() {
        int n = 5, k = 4;
        Console.WriteLine(MinKAvoidingSum(n, k));
    }
}

The Python function uses a similar loop, adding the minimal possible natural numbers to accumulate to the sum, avoiding any that would yield k as a sum with any previous number.

Complexity

Time complexity: O(n). Space complexity: O(1).

Try this approach in the editor

Approach 2: Approach with Direct Number Generation

This approach leverages mathematical deduction to directly determine the number set providing the minimum sum by considering consecutive numbers unless they have a complement already in the set adding up to k. If a conflict arises, it skips directly to numbers above k.

def min_k_avoiding_sum(n, k):
    sum_total = 0
    for i in range(1, n + 1):
        num = i
        if i >= (k + 1) // 2:
            num += k
        sum_total += num
    return sum_total - k * ((n > (k + 1) // 2) and (n - (k + 1) // 2) or 0)

n, k = 5, 4
print(min_k_avoiding_sum(n, k))
public class KAvoidingSum {
    public static int minKAvoidingSum(int n, int k) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            int num = i;
            if (i >= (k + 1) / 2) {
                num += k;
            }
            sum += num;
        }
        return sum - k * ((n > (k + 1) / 2) ? (n - (k + 1) / 2) : 0);
    }

    public static void main(String[] args) {
        int n = 5, k = 4;
        System.out.println(minKAvoidingSum(n, k));
    }
}
#include <iostream>

int min_k_avoiding_sum(int n, int k) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        int num = i;
        if (i >= (k + 1) / 2) {
            num += k;
        }
        sum += num;
    }
    return sum - k * ((n > (k + 1) / 2) ? (n - (k + 1) / 2) : 0);
}

int main() {
    int n = 5, k = 4;
    std::cout << min_k_avoiding_sum(n, k) << std::endl;
    return 0;
}
function minKAvoidingSum(n, k) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        let num = i;
        if (i >= Math.ceil((k + 1) / 2)) {
            num += k;
        }
        sum += num;
    }
    return sum - k * (Math.max(0, n - Math.ceil((k + 1) / 2)));
}

let n = 5, k = 4;
console.log(minKAvoidingSum(n, k));
#include <stdio.h>

int min_k_avoiding_sum(int n, int k) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        int num = i;
        if (i >= (k + 1) / 2) {
            num += k;
        }
        sum += num;
    }
    return sum - k * ((n > (k + 1) / 2) ? (n - (k + 1) / 2) : 0);
}

int main() {
    int n = 5, k = 4;
    printf("%d\n", min_k_avoiding_sum(n, k));
    return 0;
}
using System;

public class KAvoidingSum {
    public static int MinKAvoidingSum(int n, int k) {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            int num = i;
            if (i >= (k + 1) / 2) {
                num += k;
            }
            sum += num;
        }
        return sum - k * ((n > (k + 1) / 2) ? (n - (k + 1) / 2) : 0);
    }

    public static void Main() {
        int n = 5, k = 4;
        Console.WriteLine(MinKAvoidingSum(n, k));
    }
}

Implemented leveraging range-based arithmetic, this method calculates each element positional and compensational value if needed to circumvent oversumming.

Complexity

Handled in O(n) time and O(1) space with only variables maintained.

Try this approach in the editor

Approach 3: Greedy + Simulation

Starting from the positive integer i = 1, we sequentially determine if i can be added to the array. If it can be added, we add i to the array, accumulate it to the answer, and then mark k - i as visited, indicating that k-i cannot be added to the array. We continue this process until the array's length reaches n.

The time complexity is O(n + k), and the space complexity is O(n + k). Where n is the length of the array.

function minimumSum(n: number, k: number): number {
    let s = 0;
    let i = 1;
    const vis: boolean[] = Array(n + k + 1).fill(false);
    while (n--) {
        while (vis[i]) {
            ++i;
        }
        if (k >= i) {
            vis[k - i] = true;
        }
        s += i++;
    }
    return s;
}
func minimumSum(n int, k int) int {
	s, i := 0, 1
	vis := make([]bool, n+k+1)
	for ; n > 0; n-- {
		for vis[i] {
			i++
		}
		if k >= i {
			vis[k-i] = true
		}
		s += i
		i++
	}
	return s
}
impl Solution {
    pub fn minimum_sum(n: i32, k: i32) -> i32 {
        let (mut s, mut i) = (0, 1);
        let mut vis = std::collections::HashSet::new();

        for _ in 0..n {
            while vis.contains(&i) {
                i += 1;
            }
            vis.insert(k - i);
            s += i;
            i += 1;
        }

        s
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach with Incremental Element Selection

Time complexity: O(n). Space complexity: O(1).

Approach with Direct Number Generation

Handled in O(n) time and O(1) space with only variables maintained.

Greedy + Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Incremental Element Selection (Greedy + Set)O(n)O(n)When explaining the logic step‑by‑step or demonstrating greedy reasoning with complement checks
Direct Number Generation (Math Insight)O(n)O(1)Best optimized solution once the pattern of forbidden pairs around k is recognized

Frequently asked questions

Is Determine the Minimum Sum of a k-avoiding Array easy or hard?

LeetCode classifies this problem as Medium. The greedy idea is straightforward once you notice that pairs summing to k must be avoided, but recognizing the mathematical pattern that allows direct number generation requires some insight.

Determine the Minimum Sum of a k-avoiding Array Python/Java solution

Implement a greedy loop that keeps adding the smallest valid integer until n elements are chosen. In Python or Java, store selected numbers in a HashSet to check complements in O(1) time, or directly generate numbers from 1 to k/2 and then from k upward.

How to solve Determine the Minimum Sum of a k-avoiding Array in O(n)?

Iterate through positive integers and greedily pick the smallest valid number. Either check if k - x already exists using a hash set, or apply the mathematical observation that numbers up to k/2 can be taken safely and remaining numbers should start from k. Both methods build the array in linear time.

What is the best approach for Determine the Minimum Sum of a k-avoiding Array?

The best approach uses a greedy construction based on the observation that numbers x and k-x cannot both appear. Select numbers from 1 upward until reaching k/2, then continue from k if more elements are needed. This produces the minimum sum while maintaining the constraint in O(n) time and O(1) space.

Is Determine the Minimum Sum of a k-avoiding Array asked at Google/Amazon/Meta?

Greedy construction and complement‑avoidance patterns appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary, the underlying idea of avoiding pair sums and minimizing totals is a common interview theme.

What data structure is used in Determine the Minimum Sum of a k-avoiding Array?

The straightforward solution uses a hash set to track chosen numbers and quickly check whether the complement k - x already exists. The optimized mathematical approach removes the data structure entirely and generates numbers directly.

What is the time complexity of Determine the Minimum Sum of a k-avoiding Array?

Both common solutions run in O(n) time where n is the required array size. The greedy set-based method also uses O(n) extra space to track chosen values, while the direct math-based generation runs in O(1) space.

Comments

Now write it yourselfClose this page and solve Determine the Minimum Sum of a k-avoiding Array in the editor, without looking.
Practise Determine the Minimum Sum of a k-avoiding Array