This question on LeetCode is good practice for sliding window problems. Of course, we can solve it easily using a collections Map, but it's interesting and efficient to apply the sliding window algorithm to tackle it.
We can follow the diagram I created below step by step.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Time complexity: O(n) // Space complexity: O(n) classSolution { publicbooleancontainsNearbyDuplicate(int[] nums, int k) { HashSet<Integer> set = newHashSet<>(); for(int i=0;i<nums.length;i++) { // Step 1: Check if there is duplicate among the set if(!set.add(nums[i])) { returntrue; } // Step 2: Remove the first element in the set if(set.size()>k) { set.remove(nums[i-k]); } }