#2195
Append K Integers With Minimal Sum
MediumArrayMathGreedySortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach leverages the fact that the smallest k unique positive integers not in nums will always yield the minimum sum. We can efficiently find these integers by iterating through positive integers and checking against a set of existing numbers.
⚙️
Algorithm
5 steps- 1Step 1: Create a set from nums for O(1) lookups.
- 2Step 2: Initialize a variable to keep track of the sum of the k unique integers.
- 3Step 3: Use a loop starting from 1 to find the first k integers not in the set.
- 4Step 4: Add these integers to the sum.
- 5Step 5: Return the sum.
solution.py12 lines
1# Full working Python code
2
3def minimal_sum(nums, k):
4 num_set = set(nums)
5 sum_unique = 0
6 current = 1
7 while k > 0:
8 if current not in num_set:
9 sum_unique += current
10 k -= 1
11 current += 1
12 return sum_uniqueℹ
Complexity note: The time complexity is O(n) because we are iterating through the integers and checking against the set, which is O(1) per check. The space complexity is O(n) for storing the elements of nums in the set.
- 1The smallest k unique integers will always yield the minimal sum.
- 2Using a set allows for quick lookups to check if an integer is already in nums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.