199. Contains Duplicate II
You get an integer array nums and a non-negative integer k. This time a duplicate only counts if it is nearby: return true when there exist two distinct positions i and j with nums[i] == nums[j] and |i - j| <= k, and false otherwise.
In other words, the same value must appear twice within a window of k positions. Note that k = 0 can never be satisfied — two distinct indices are always at least 1 apart.
Example 1:
Input: nums = [1, 2, 3, 1], k = 3
Output: true
Explanation: nums[0] and nums[3] are both 1 and |0 - 3| = 3 <= k.
Example 2:
Input: nums = [1, 0, 1, 1], k = 1
Output: true
Explanation: nums[2] and nums[3] are both 1 and only 1 apart.
Example 3:
Input: nums = [1, 2, 3, 1, 2, 3], k = 2
Output: false
Explanation: Every repeated value sits exactly 3 positions from its twin, which is farther than k = 2.
Constraints:
- 1 ≤ nums.length ≤ 10⁵
- -10⁹ ≤ nums[i] ≤ 10⁹
- 0 ≤ k ≤ 10⁵
Hints:
For each value you only care about the *most recent* index where it appeared — anything older is farther away.
Keep a hash map value → last index. When you meet the value again, compare the index gap to k, then update the map.
Alternatively, maintain a set holding exactly the last k elements (a sliding window): if the incoming element is already in the set, the answer is true. Evict nums[i - k] as the window slides.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [1, 2, 3, 1], k = 3
Expected output: true