Contains Duplicate II(#219)
Category: Array, Hash Set, Sliding Window
๐งฉ Problem Statement
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`.
๐ Examples
Input: nums = [1, 2, 3, 1], k = 3
Output: true
Input: nums = [1, 0, 1, 1], k = 1
Output: true
Input: nums = [1, 2, 3, 1, 2, 3], k = 2
Output: false
๐ง Approach
Approach 1. Brute Force Approach:
โข Iterate through each element in the array using index `i`.
โข For each `i`, check the next `k` elements to see if any are equal to `nums[i]`.
โข If found, return true.
Approach 2. Optimized Sliding Window Approach:
โข Use a Set to maintain the last `k` elements we've seen.
โข Loop through the array:
โข If the current element is already in the Set, return true.
โข Otherwise, add it to the Set.
โข If the Set size exceeds `k`, remove the element that falls out of the window range.
โข if no duplicates found within range `k`, return false.
๐ป Code
/* Brute Force Approach */
var containsNearbyDuplicate = function(nums, k) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j <= i + k && j < nums.length; j++) {
if (nums[i] === nums[j]) return true;
}
}
return false;
};
/* Optimized Sliding Window Approach */
var containsNearbyDuplicate = function(nums, k) {
const set = new Set();
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;
};
๐ Complexity
Time: O(n)
Space: O(min(n, k))