Use hash map to track last occurrence index of each element.
1class Solution {
2 public boolean containsNearbyDuplicate(int[] nums, int k) {
3 Map<Integer, Integer> seen = new HashMap<>();
4
5 for (int i = 0; i < nums.length; i++) {
6 if (seen.containsKey(nums[i]) && i - seen.get(nums[i]) <= k) {
7 return true;
8 }
9 seen.put(nums[i], i);
10 }
11
12 return false;
13 }
14}