I think the easiest method to understand, is maintaining a set whose size is at most k. If a element is found in the set, then return true; otherwise, add it to the set; and if the size is bigger than k, remove the nums[index - k] from the set to keep its size at most k

```
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(!set.add(nums[i])){
return true;
}
if(set.size() > k){
set.remove(nums[i-k]);
}
}
return false;
}
}
```