Contains Duplicate II Visualizer & Step-by-Step Algorithm Solution

Determine if there are two distinct indices i and j such that nums[i] == nums[j] and abs(i - j) <= k using a sliding window hash set.

Category: sliding-window | Difficulty: Easy

Tags: Sliding Window, Hash Set, Array

Contains Duplicate II

Numbers Array (length: 4)
1
0
2
1
3
2
1
3
SLIDING WINDOW SET (k ≤ 3)
(Empty Set)
100%
state
k3
window size0
Initialization
1/15
Explanation

Starting containsNearbyDuplicate with array [1, 2, 3, 1] and max distance k = 3.

Source Code
1function containsNearbyDuplicate(nums: number[], k: number): boolean {
2 if (k <= 0) return false;
3
4 const set = new Set<number>();
5 let left = 0;
6
7 for (let right = 0; right < nums.length; right++) {
8 if (right - left > k) {
9 set.delete(nums[left]);
10 left++;
11 }
12
13 if (set.has(nums[right])) return true;
14
15 set.add(nums[right]);
16 }
17
18 return false;
19}