Contains duplicate II


Solution

  • Problem. I thought the most efficient way to find a duplicate would be to iterate over an array and write encountered duplicates to dictionary using number as its key and Array<indexes> as value. And script would iterate over the former array while main loop is running and compare the current index with the indexes stored in dictionary. But after peeking the solutions tab I found more performant solution that uses sliding window technique.

My solution:

function containsNearbyDuplicate(nums: number[], k: number): boolean {
    const map = {};

    for(let i = 0; i < nums.length; i++){
        if(map[nums[i]] !== undefined){
            for(let j = 0; j < map[nums[i]].length; j++){
                if(Math.abs(i - map[nums[i]][j]) <= k){
                    return true
                }
            }
            map[nums[i]].push(i)
        }else{
            map[nums[i]] = [i]
        }
    }

    return false
};

Code copied form solutions tab:

function containsNearbyDuplicate(nums: number[], k: number): boolean {
    let set = new Set<number>();
    
    for (let i = 0; i < nums.length; i++) {
        if (set.has(nums[i])) return true;
        set.add(nums[i]);
        if (set.size > k) set.delete(nums[i - k]);
    }
    return false;
}