Skip to content

2598. Smallest Missing Non-negative Integer After Operations 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int findSmallestInteger(vector<int>& nums, int value) {
    unordered_map<int, int> count;

    for (const int num : nums)
      ++count[(num % value + value) % value];

    for (int i = 0; i < nums.size(); ++i)
      if (--count[i % value] < 0)
        return i;

    return nums.size();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int findSmallestInteger(int[] nums, int value) {
    Map<Integer, Integer> count = new HashMap<>();

    for (final int num : nums)
      count.merge((num % value + value) % value, 1, Integer::sum);

    for (int i = 0; i < nums.length; ++i) {
      if (count.getOrDefault(i % value, 0) == 0)
        return i;
      count.merge(i % value, -1, Integer::sum);
    }

    return nums.length;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def findSmallestInteger(self, nums: list[int], value: int) -> int:
    count = collections.Counter([num % value for num in nums])

    for i in range(len(nums)):
      if count[i % value] == 0:
        return i
      count[i % value] -= 1

    return len(nums)