Smallest Missing Non-negative Integer After Operations - Problem

You are given a 0-indexed integer array nums and an integer value.

In one operation, you can add or subtract value from any element of nums.

For example, if nums = [1,2,3] and value = 2, you can choose to subtract value from nums[0] to make nums = [-1,2,3].

The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.

For example, the MEX of [-1,2,3] is 0 while the MEX of [1,0,3] is 2.

Return the maximum MEX of nums after applying the mentioned operation any number of times.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,10,3], value = 6
Output: 0
💡 Note: We have remainders [1,4,3] mod 6. To achieve MEX ≥ 1, we need to create value 0, which requires an element with remainder 0 mod 6. Since we don't have any element with remainder 0, the maximum MEX is 0.
Example 2 — Zero Value
$ Input: nums = [3,4,1,9], value = 0
Output: 0
💡 Note: When value=0, we cannot transform any elements. The array remains [3,4,1,9]. The MEX is 0 since 0 is not present.
Example 3 — Perfect Consecutive
$ Input: nums = [0,1,4,5], value = 3
Output: 4
💡 Note: We can transform: 0→0, 1→1, 4→1 (subtract 3), 5→2 (subtract 3). This gives remainders 0,1,1,2 mod 3. We can make consecutive sequence [0,1,2,3] by using the elements optimally.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109
  • 1 ≤ value ≤ 105

Visualization

Tap to expand
Smallest Missing Non-negative Integer INPUT nums array: 1 idx 0 10 idx 1 3 idx 2 value: 6 Remainders (mod 6): 1%6=1 10%6=4 3%6=3 Remainders: {1, 4, 3} Can reach: 1, 7, 13... 4, 10, 16... | 3, 9, 15... ALGORITHM STEPS 1 Compute Remainders nums[i] % value for each 2 Count Frequencies Track how many per remainder Remainder counts: r=0: 0 r=1: 1 r=2: 0 r=3: 1 r=4: 1 r=5: 0 3 Greedy Assignment Assign smallest to each r 4 Find First Gap 0%6=0 -- No element! 1%6=1 -- Use nums[0]=1 2%6=2 -- No element! FINAL RESULT Scanning for MEX: 0: r=0, count=0 FAIL 1: r=1, count=1 OK Cannot produce 0: No number with remainder 0 Can produce 1: nums[0]=1 already equals 1 Cannot produce 2: No number with remainder 2 MEX = 2 Maximum achievable Key Insight: Numbers reachable via +/- value share the same remainder (mod value). Each remainder class can produce exactly one non-negative integer per element. Greedily assign smallest targets to each remainder, then find first unreachable integer. Time: O(n), Space: O(value). TutorialsPoint - Smallest Missing Non-negative Integer After Operations | Optimal Greedy Assignment
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
4.2K Views
Medium Frequency
~25 min Avg. Time
185 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