DDSA
Advertisement

219. Contains Duplicate II

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

Approach

Store each value’s most recent index in a HashMap; return true if the gap between the current and previous index is at most k.

219.cs
C#
// Approach: Store each value’s most recent index in a HashMap; return true
// if the gap between the current and previous index is at most k.
// Time: O(n) Space: O(n)

public class Solution
{
    public bool ContainsNearbyDuplicate(int[] nums, int k)
    {
        Dictionary<int, int> map = new Dictionary<int, int>();
        int n = nums.Length;

        for (int i = 0; i < n; i++)
        {
            if (map.ContainsKey(nums[i]))
            {
                int prevIndex = map[nums[i]];
                int value = Math.Abs(prevIndex - i);
                if (value <= k)
                    return true;
                map[nums[i]] = i;
            }
            else
            {
                map.Add(nums[i], i);
            }
        }

        return false;
    }
}
Advertisement
Was this solution helpful?