Contains Duplicate II - Problem
You are given an integer array nums and a distance threshold k. Your task is to determine if there are any duplicate elements within a specific range.
More specifically, return true if there exist two distinct indices i and j in the array such that:
nums[i] == nums[j](the elements are equal)abs(i - j) <= k(the indices are at mostkpositions apart)
Otherwise, return false.
Example: In array [1,2,3,1] with k=3, we find that nums[0] = nums[3] = 1 and abs(0-3) = 3 <= 3, so we return true.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,2,3,1], k = 3
โบ
Output:
true
๐ก Note:
The value 1 appears at indices 0 and 3. The distance between these indices is |3-0| = 3, which is exactly equal to k=3, so we return true.
example_2.py โ No Valid Duplicates
$
Input:
nums = [1,0,1,1], k = 1
โบ
Output:
true
๐ก Note:
The value 1 appears at indices 0, 2, and 3. The distance between indices 2 and 3 is |3-2| = 1, which equals k=1, so we return true.
example_3.py โ Distance Too Large
$
Input:
nums = [1,2,3,1,2,3], k = 2
โบ
Output:
false
๐ก Note:
Although there are duplicates (1 appears at indices 0,3 and 2 appears at indices 1,4), all duplicate pairs have distances greater than k=2, so we return false.
Constraints
- 1 โค nums.length โค 105
- -109 โค nums[i] โค 109
- 0 โค k โค 105
- Note: Two distinct indices means i โ j
Visualization
Tap to expand
Understanding the Visualization
1
Book Registry
Keep a record of when each book was last checked out (hash map)
2
New Checkout
When someone wants to check out a book, look up the last checkout date
3
Time Check
If the same book was checked out within k days, flag it as a violation
4
Update Record
Update the registry with the new checkout date
Key Takeaway
๐ฏ Key Insight: We only need to remember the most recent occurrence of each element, not all historical positions. This reduces both time and space complexity significantly!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code