My simple solution in Java using HashMap

• Iterate through array and use HashMap to save `number[i]` as a key and `i` as a value. If the map already contains `number[i]` - subtract `map.get(number[i])` from `i` and return true if result is less or equal to `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;
}
map.put(nums[i], i);
}
return false;
}``````

• But this wont work for this case right? [1,2,3,4,5,1,6,1] k=2, the hash will put <1,0> and it will compute distance between the second 1 which will be 5 and the third 1 which is 6 while there is a solution

• This post is deleted!

• It will work fine in your case, because `<key, value> 1 -> 0` pair in the HashMap will be overwritten to `<key, value> 1 -> 5` ...

• ah sorry I missed that line :) thanks (Y)

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.