Smallest Missing Non-negative Integer After Operations - Problem

You're given an integer array nums and a special value. Your mission is to maximize the MEX (minimum excluded value) of the array by strategically adding or subtracting the given value from any elements.

What is MEX? The MEX of an array is the smallest non-negative integer that doesn't appear in the array. For example:

  • MEX of [-1, 2, 3] is 0 (since 0 is missing)
  • MEX of [1, 0, 3] is 2 (since 2 is missing)

Operations allowed: You can perform unlimited operations where each operation adds or subtracts value from any array element.

Example: If nums = [1, 2, 3] and value = 2, you could subtract 2 from the first element to get [-1, 2, 3], making the MEX = 0.

๐ŸŽฏ Goal: Return the maximum possible MEX after performing any number of operations.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, -10, 7, 13, 6, 8], value = 5
โ€บ Output: 4
๐Ÿ’ก Note: We can transform: 1โ†’1, -10โ†’0 (add 10=2ร—5), 7โ†’2 (subtract 5), 13โ†’3 (subtract 10=2ร—5), giving us [1, 0, 2, 3, 6, 8]. The MEX is 4 since we have {0, 1, 2, 3} but missing 4.
example_2.py โ€” All Same Remainder
$ Input: nums = [1, 4, 7, 10], value = 3
โ€บ Output: 1
๐Ÿ’ก Note: All numbers have remainder 1 when divided by 3. We can only create one number with remainder 0 by transforming one element. Best we can do is [0, 4, 7, 10] โ†’ MEX = 1.
example_3.py โ€” Edge Case Small Array
$ Input: nums = [3], value = 1
โ€บ Output: 1
๐Ÿ’ก Note: We can transform 3 to 0 (subtract 3ร—1), giving us [0]. The MEX is 1 since we have 0 but missing 1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค value โ‰ค 105
  • The answer is guaranteed to be in the range [0, nums.length]

Visualization

Tap to expand
๐ŸŽฐ Number Slots MachineFill consecutive slots 0, 1, 2, 3... using adjustable tokens012345โœ“โœ“โœ“โœ“โœ“โœ—MEX = 5 (First Empty Slot)Token Buckets (Grouped by Remainder):R0Count: 2R1Count: 2R2Count: 1R0Count: 0๐ŸŽฏ Greedy Strategy1. Group tokens by remainder2. Fill slots 0,1,2,3... in order3. Stop at first unfillable slotTime: O(n) | Space: O(min(n, value)) | Always Optimal! โšก
Understanding the Visualization
1
Group Your Tokens
Sort tokens into buckets based on their remainder when divided by the increment value
2
Fill Slots Greedily
Starting from slot 0, use tokens from the appropriate bucket to fill each consecutive slot
3
Find First Empty
The first slot you can't fill gives you the maximum MEX
Key Takeaway
๐ŸŽฏ Key Insight: Elements with the same remainder modulo `value` can be transformed into each other. Group by remainder, then greedily assign to consecutive positions for optimal MEX.
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 25
78.4K Views
High Frequency
~25 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