Use a set with size at most k, might be very easy to understand.

  • 0

    I think the easiest method to understand, is maintaining a set whose size is at most k. If a element is found in the set, then return true; otherwise, add it to the set; and if the size is bigger than k, remove the nums[index - k] from the set to keep its size at most k

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            HashSet<Integer> set = new HashSet<Integer>();
            for(int i = 0; i < nums.length; i++){
                    return true;
                if(set.size() > k){
            return false;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.