Append K Integers With Minimal Sum - Problem

You're given an integer array nums and an integer k. Your task is to append exactly k unique positive integers to the array that don't already exist in nums.

The challenge? You must choose these k integers such that their total sum is minimized. In other words, you want to add the k smallest possible positive integers that aren't already present in the array.

Goal: Return the sum of the k integers you append to nums.

Example: If nums = [1, 4, 25, 10, 25] and k = 2, the smallest missing positive integers are 2 and 3, so you'd return 2 + 3 = 5.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,4,25,10,25], k = 2
โ€บ Output: 5
๐Ÿ’ก Note: The smallest missing positive integers are 2 and 3. Since 2 + 3 = 5, we return 5.
example_2.py โ€” Sequential Start
$ Input: nums = [5,6], k = 6
โ€บ Output: 25
๐Ÿ’ก Note: The missing numbers are [1,2,3,4,7,8]. We need k=6 numbers, so we take all of them: 1+2+3+4+7+8 = 25.
example_3.py โ€” Edge Case
$ Input: nums = [1,2,3,4], k = 2
โ€บ Output: 11
๐Ÿ’ก Note: Numbers 1,2,3,4 are already present. The next smallest missing numbers are 5 and 6, so 5 + 6 = 11.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค k โ‰ค 2 ร— 108
  • Note: k can be very large, so efficient calculation is crucial

Visualization

Tap to expand
Finding K=2 Cheapest Missing NumbersNumber Line Street (Parking Spots):๐Ÿš— = Taken (in nums), ๐Ÿ…ฟ๏ธ = Available (missing), ๐Ÿ’ฐ = Selected๐Ÿš—1๐Ÿ’ฐ2๐Ÿ’ฐ3๐Ÿš—4๐Ÿ…ฟ๏ธ5Step-by-Step Process:1. Sort & dedupe: nums = [1, 4, 25, 10] โ†’ [1, 4, 10, 25]2. Find gap [2,3] between 1 and 4 (size = 2)3. We need k=2 numbers โ†’ take both 2 and 3 from this gapMathematical Formula:Sum of range [2,3] = 2 ร— (2ร—2 + 2-1) รท 2 = 2 ร— 5 รท 2 = 5 โœ…๐ŸŽฏ Result: 2 + 3 = 5
Understanding the Visualization
1
Survey Taken Spots
Identify all occupied positions (existing numbers in nums)
2
Find Empty Ranges
Look for consecutive empty spots between occupied positions
3
Calculate Range Costs
Use math formulas to quickly calculate the total cost of each empty range
4
Fill Cheapest First
Take numbers from the cheapest ranges first until we have k numbers
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking each number individually, we can mathematically calculate the sum of entire ranges of missing numbers using arithmetic progression formulas, making the solution efficient even for very large k values!
Asked in
Google 42 Amazon 35 Apple 28 Meta 22
52.3K Views
Medium-High Frequency
~22 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen