Problem Description
Given an integer array nums and an integer k, append k unique positive integers that do not appear in nums such that the sum of the k appended numbers is minimized. Return the sum of these appended integers.
Key Insights
- The smallest numbers yield the minimal sum; therefore, consider positive integers starting from 1.
- Avoid numbers already present in nums.
- Sorting the unique values in nums helps identify “gaps” where missing numbers can be efficiently selected.
- Instead of iterating one by one (which can be inefficient for large k), use arithmetic sum formulas for consecutively missing numbers.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the unique values from nums.
Space Complexity: O(n) for storing the unique numbers.
Solution
- Convert nums to a set and then to a sorted list to eliminate duplicates and process in order.
- Initialize a candidate variable to 1.
- Iterate over each number in the sorted list:
- For each number, if there is a gap between the candidate and the current number, determine how many missing numbers can be picked from the gap.
- If the gap contains more missing integers than needed (k remains), use the arithmetic series formula to add the sum of the required count and update candidate accordingly.
- Otherwise, add the entire gap, subtract the count from k, and move the candidate past the current number.
- After processing the sorted nums, if k is still positive, add the k consecutive integers starting from candidate using the arithmetic series formula.
- Return the computed sum.