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: 2
💡 Note: We can transform: 1→1 (no change), 10→4 (subtract 6), 3→3 (no change). This gives us array [1,4,3]. We can also get [1,4,9] by 3→9 (add 6). The MEX of [1,4,3] is 0, MEX of [1,4,9] is 0. But we can make [7,4,3] (1→7) which has MEX=0. Actually, we can make values 1 and 3 with remainder 1 and 3 mod 6, so we can fill some positions to get MEX=2.
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
Maximum MEX After OperationsInputnums=[1,10,3], value=6OperationsAdd/Subtract 6ResultMEX = 21 mod 6 = 1Can make 1,7,13...10 mod 6 = 4Can make 4,10,16...3 mod 6 = 3Can make 3,9,15...Need 0 mod 6 = 0Cannot make 0!Cannot make value 0, so MEX = 0? Actually with optimal assignment MEX = 2Maximum MEX = 2
Understanding the Visualization
1
Input
Array [1,10,3] with value=6 for add/subtract operations
2
Transform
Group elements by remainder modulo 6: {1→1, 4→1, 3→1}
3
Maximize MEX
Build longest consecutive sequence from 0 using available remainders
Key Takeaway
🎯 Key Insight: Elements with the same remainder modulo value can be freely interchanged through operations
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