```
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<>();
int curr = 0;
int length = nums.length;
while (set.size() < k && curr < length) {
if (set.contains(nums[curr])) return true;
else set.add(nums[curr]);
curr++;
}
int front = 0;
while (curr < length) {
if (set.contains(nums[curr])) return true;
else {
set.add(nums[curr]);
set.remove(nums[front]);
front++;
curr++;
}
}
return false;
}
```

Build a slide window to store the first k objects (if applicable), and remove a front object and add a new object in the set. Space: O(k), Time: O(n).