Skip to content

Instantly share code, notes, and snippets.

@Ephraimiyanda
Created February 3, 2026 22:11
Show Gist options
  • Select an option

  • Save Ephraimiyanda/f159d739a5cde5ba1aa8338e0b64b35c to your computer and use it in GitHub Desktop.

Select an option

Save Ephraimiyanda/f159d739a5cde5ba1aa8338e0b64b35c to your computer and use it in GitHub Desktop.
Contains Duplicate II

Approach

  1. using a hashmap i check if a number exists in the map, if it doesnt then i store the index of the number in the map.
  2. if the number exists in the map the next time the number is seen in the array the absolute difference between the index of the previously stored number and its current duplicate is checked.
  3. if the difference is less than or equal to k i return true

Complexity

  • Time complexity:O(N)

  • Space complexity:O(N)

Code

function containsNearbyDuplicate(nums: number[], k: number): boolean {
    let map = new Map()
    for (let i = 0; i < nums.length; i++) {

        if (map.has(nums[i]) && Math.abs(i - map.get(nums[i])) <= k) {
            return true;
        }
         map.set(nums[i], i)
        
    }
    return false
};
scrnli_zx3y3470M5j0z7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment