Sliding Window

mail@pastecode.io avatar
unknown
java
a year ago
730 B
3
Indexable
Never
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashSet<Integer> kWindowSet = new HashSet<>();
        int start = 0;
        int end = 0;
        while (end < nums.length) {
            int windowLen = end - start;

            if (windowLen > k) {
                kWindowSet.remove(nums[start]);
                start++;
            }
            // put the number into the windowSet, if the number already exists , we have a solution 
            // we have a number into our hand and a prev number within the k range (window)
            if (kWindowSet.contains(nums[end])) return true;
            kWindowSet.add(nums[end]);
            end++;
        }

        return false;
    }
}