Untitled

 avatar
unknown
plain_text
a month ago
804 B
1
Indexable
import java.util.HashSet;

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashSet<Integer> set = new HashSet<>();
        int i = 0, j = 0; // i is the left pointer, j is the right pointer

        while (j < nums.length) {
            // Expand the window by adding the current element
            if (set.contains(nums[j])) {
                return true; // Duplicate found
            }
            set.add(nums[j]);

            // Shrink the window if it exceeds size k
            if (j - i >= k) {
                set.remove(nums[i]);
                i++; // Move the left pointer
            }

            j++; // Move the right pointer
        }

        return false; // No duplicates found within the required range
    }
}
Leave a Comment