Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Given an array of numbers A, which might contain duplicate elements, How do we find if there are two elements A[i], A[j] such that i, j are distinct and the difference between them is at most k?
public boolean containsNearbyDuplicate(int[] nums, int k)
{
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++ )
{
if(map.containsKey(nums[i]) && i-map.get(nums[i]) <= k)
return true;
else
map.put(nums[i],i);
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment