DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 219. Contains Duplicate II (javascript solution)

Description:

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

var containsNearbyDuplicate = function(nums, k) {
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
    // Check if the difference betweend duplicates is less than k
    if (i - map.get(nums[i]) <= k) {
      return true;
    }
    map.set(nums[i], i);
  }
  return false;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)