Simple Java solution with explained

  • 0
     public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(nums.length < 2 || k == 0) return false;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer> ();
        for(int i = 0; i < nums.length; i++) {
            int a = nums[i];
            if(map.containsKey(a) ) {
                int b = map.get(a);
                if(i - b <= k) return true;
            map.put(a, i);
        return false;

    The algorithm is pretty simple O(n) space and time. I just used a hash map that maps the value at num[i] to i. If the map already contains num[i] then you take the value that maps from it from the hash map. If the distance from these two values is less than or equal to k then just return true. Otherwise just keep replacing the previous value with the one you just found ( since we are basically concerned with minimizing j - i )

  • 0

    When you try [2,2] 3 ?

Log in to reply

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