Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

Solution

public class Solution {
    public bool ContainsNearbyDuplicate(int[] nums, int k) {
        HashSet<int> set = new HashSet<int>();
        for(int i=0;i<nums.Length;i++)
        {
            if(i > k)
            {
                set.Remove(nums[i-k-1]);
            }
            if(set.Contains(nums[i]))
                return true;
            else
                set.Add(nums[i]);
        }
        return false;
    }
}

Code Walk through

value = [ 1, 2, 3, 1]

index = [ 0, 1, 2, 3]

k = 3

i = 0;
set = { 1 }

i = 1;
set = { 1, 2}

i = 2;
set = { 1, 2, 3}

i = 3;
set = {1, 2, 3, 1} ----> Return True
value = [1,2,3,1,2,3]
index = [0,1,2,3,4,5]

k = 2

i = 0;
set = {1}


i = 1;
set = {1,2}

i = 2;
set = {1,2,3}

i = 3;
k = 2;
i > k -- So remove (i - k - 1) => 0th index element -- that is 1
so set will be - {2,3}

Now add the element as asusual in set
set = {2,3,1} 

i = 4;
k = 2;
i > k -- So remove (i - k - 1) => 1st index element -- that is 2
so set will be - {3,1}

Now add the element as asusual in set
set = {3,1,2} 

i = 5;
k = 2;
i > k -- So remove (i - k - 1) => 2nd index element -- that is 3
so set will be - {1,2}

Now add the element as asusual in set
set = {1,2,3} 


-----> Return False