1class Solution {
2 public boolean containsNearbyDuplicate(int[] nums, int k) {
3 HashMap<Integer, Integer> map = new HashMap<>();
4
5 for (int i = 0; i < nums.length; i++) {
6 // Check if number exists and distance <= k
7 if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
8 return true;
9 }
10 // Update latest index of current number
11 map.put(nums[i], i);
12 }
13
14 return false;
15 }
16}