[LeetCode] Smallest Missing Non-negative Integer After Operations

2598. Smallest Missing Non-negative Integer After Operations

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Solution {
public:
int findSmallestInteger(vector<int>& A, int value) {
int res = 0;
unordered_map<int, int> x;
for(auto a : A) {
if(a >= 0) x[a%value] += 1;
else {
a %= value;
x[(a + value) % value]+=1;
}
}
while(x[res % value]) {
x[res%value] -= 1;
res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/19/PS/LeetCode/smallest-missing-non-negative-integer-after-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.