Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created August 2, 2015 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravichandrae/123229f5b8e1ee157ebd to your computer and use it in GitHub Desktop.
Save ravichandrae/123229f5b8e1ee157ebd to your computer and use it in GitHub Desktop.
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