#2598
Smallest Missing Non-negative Integer After Operations
MediumArrayHash TableMathGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages modular arithmetic to determine which integers can be formed. By grouping numbers based on their remainder when divided by `value`, we can efficiently find the maximum MEX.
⚙️
Algorithm
3 steps- 1Step 1: Create a set to store the reachable integers based on their remainders when divided by `value`.
- 2Step 2: For each number in `nums`, calculate its effective value as `num % value` and add it to the set if it is non-negative.
- 3Step 3: Iterate from 0 upwards, checking if each integer is in the set. The first integer not found is the maximum MEX.
solution.py12 lines
1# Full working Python code
2
3def max_mex(nums, value):
4 reachable = set()
5 for num in nums:
6 if num >= 0:
7 reachable.add(num % value)
8 mex = 0
9 while mex in reachable:
10 mex += 1
11 return mex
12ℹ
Complexity note: The time complexity is linear because we traverse the list once to populate the set and then check for MEX in a linear manner.
- 1Using modular arithmetic allows us to efficiently determine which integers can be formed.
- 2The MEX is determined by checking sequentially from 0 upwards, making it easy to find the first missing integer.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.