Javascript solution


  • 0
    C
    • keep track of each character and its last index
    • if char exists already, then compare last index to curr index, if it is within the k range then return true
    • else return false at the end of the loop
    var containsNearbyDuplicate = function(nums, k) {
        var dict = {};
        for (var i = 0; i < nums.length; i++) {
            var char = nums[i];
            if (!dict.hasOwnProperty(char)) { 
                dict[char] = i;
            } else {
                var previousIndex = dict[char];
                var diff = i - previousIndex;
                if (diff <= k) {
                    return true
                }
                dict[char] = i;
            }
        }
        return false;
    };
    

Log in to reply
 

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