Determine the Minimum Sum of a k-avoiding Array — LeetCode 2829 Python Solution

MediumGreedyMath
Problem
#2829
Pattern
Greedy
Reading time
2 min

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.

Example

Input
n = 5, k = 4
Output
18
Explanation
Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.

Python solution

Python
class Solution:
    def minimumSum(self, n: int, k: int) -> int:
        s, i = 0, 1
        vis = set()
        for _ in range(n):
            while i in vis:
                i += 1
            vis.add(k - i)
            s += i
            i += 1
        return s

Complexity

MeasureComplexity
TimeO(n + k)
SpaceO(n + k) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array?
LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array?
The Python solution on this page runs in O(n + k).
What is the space complexity of LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array?
The Python solution on this page uses O(n + k) auxiliary space.
What topics does LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array cover?
LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array is tagged Greedy and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview