DDSA Solutions

2598. Smallest Missing Non-negative Integer After Operations

Time: O(n)
Space: O(value)

Problem Overview

Smallest Missing Non-negative Integer After Operations (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Map each element to remainder mod value; find smallest integer with no fully-filled bucket.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Map each element to remainder mod value; find smallest integer with no fully-filled bucket.

Related patterns: Array, Hash Table, Greedy

2598.cs
C#
// Approach: Map each element to remainder mod value; find smallest integer with no fully-filled bucket.
// Time: O(n) Space: O(value)

public class Solution
{
    public int FindSmallestInteger(int[] nums, int value)
    {
        Dictionary<int, int> count = new Dictionary<int, int>();

        foreach (var num in nums)
        {
            int key = (num % value + value) % value;
            if (count.ContainsKey(key))
                count[key]++;
            else
                count[key] = 1;
        }

        for (int i = 0; i < nums.Length; ++i)
        {
            if (!count.ContainsKey(i % value) || count[i % value] == 0)
                return i;
            count[i % value]--;
        }

        return nums.Length;
    }
}
Was this solution helpful?

Related Problems