Contains Duplicate II - Problem

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.

In other words, find if there are duplicate values within a window of size k.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,1], k = 3
Output: true
💡 Note: There are two 1's at indices 0 and 3. The distance |3-0| = 3 which equals k=3, so return true.
Example 2 — Distance Too Large
$ Input: nums = [1,0,1,1], k = 1
Output: true
💡 Note: There are two 1's at indices 2 and 3. The distance |3-2| = 1 which equals k=1, so return true.
Example 3 — No Duplicates Within k
$ Input: nums = [1,2,3,1,2,3], k = 2
Output: false
💡 Note: No duplicate values exist within distance k=2. The closest duplicates are at distance 3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 105

Visualization

Tap to expand
Contains Duplicate II: nums = [1,2,3,1], k = 31231i=0i=1i=2i=3Distance = |3-0| = 3Check: distance ≤ k?3 ≤ 3 ✓ Duplicate found!Output: true
Understanding the Visualization
1
Input
Array with potential duplicates and distance k
2
Process
Check if any duplicates exist within distance k
3
Output
Return true if found, false otherwise
Key Takeaway
🎯 Key Insight: Use a sliding window to efficiently track recent elements and detect duplicates within the allowed distance
Asked in
Amazon 12 Apple 8 Microsoft 6 Google 4
145.0K Views
Medium Frequency
~15 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen