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 INPUT nums array: 1 i=0 2 i=1 3 i=2 1 i=3 Duplicate! nums = [1,2,3,1] k = 3 Window size = 3 Window: |3-0| = 3 <= k ALGORITHM STEPS 1 Create Hash Map Store value --> last index 2 Iterate Array Check each element 3 Check Condition If exists and |i-j| <= k 4 Update Map Store current index Hash Map State: Value Index Step 1 0 map[1]=0 2 1 map[2]=1 3 2 map[3]=2 1 3 Found! 1 exists! |3-0|=3 <= 3 FINAL RESULT true Duplicate Found! Details: nums[0] = 1 nums[3] = 1 Same value: OK |3 - 0| = 3 <= 3: OK Time: O(n) Space: O(min(n,k)) Key Insight: Use a Hash Map to track the most recent index of each value. When we encounter a value that already exists in the map, check if the distance between indices is within k. Only store the last occurrence since we want minimum distance to current index. TutorialsPoint - Contains Duplicate II | Hash Map with Last Index Approach
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