Given an a list of array nums and a target number k, return true if there are two i and j in the array indices such that nums[i] == nums[j] and abs(i - j) <= k.
Example
nums = 1,4,3,1,9
k = 2
Answer: False
Example
nums = 10,4,3,1,9,1
k = 2
Answer: True
Solution:
Dictionaries can be used to solve this problem.
we need to check the dictionary if you already saved it, and if you already save this number, will calculate the distance between this number and the previously saved number, and if that gap is less than or equal to the target value we return true. otherwise, will replace the key with this new number and we keep searching for the new gap.
public bool ContainsNearbyDuplicate(int[] nums, int k) {
Dictionary<int, int> dict = new();
for (int i = 0; i < nums.Length; i++)
{
if (!dict.ContainsKey(nums[i]))
dict.Add(nums[i], i);
else
{
int start = dict[nums[i]];
int end = i;
int diff = Math.Abs(start - end);
if (diff <= k)
return true;
else
{
dict.Remove(nums[i]);
dict.Add(nums[i], i);
}
}
}
return false;
}
}