code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

219 Contains Duplicate 2

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const containsDuplicate = (nums, k) => {
  let map = new Map()
  for (let i = 0; i < nums.length; i++) {
    if (map.has(nums[i])) {
      if (Math.abs(map.get(nums[i]) - i) <= k) {
        return true
      }
    }
    map.set(nums[i], i)
  }
  return false
}

console.log(containsDuplicate([1, 2, 3, 1], 3))

Created 2023-05-13T14:37:58+01:00 · Edit