Solving tips
- Recognize a fixed-size sliding window: you only need to know if a value repeated within the last k positions, answered in O(1) with a hash set.
- Maintain a set of the last k values; check membership first, add the current value, then evict nums[i-k] when the set exceeds k entries.
- Alternative: a last-seen-index dict, returning True when i - last_seen[x] <= k.
- Target O(n) time and O(min(n,k)) space; watch the off-by-one since |i-j|<=k spans k+1 indices, so keep the set at most k values.
Problem
Given an integer array nums and an integer k, decide whether the array contains two distinct indices i and j such that nums[i] == nums[j] and the indices are close together: abs(i - j) <= k. Return True if such a pair exists, False otherwise.
In other words: does any value repeat within a window of k + 1 consecutive positions?
Examples
nums = [1, 2, 3, 1],k = 3→True— the two1s sit at indices 0 and 3, and3 - 0 = 3 <= k.nums = [1, 0, 1, 1],k = 1→True— the1s at indices 2 and 3 are adjacent.nums = [1, 2, 3, 1, 2, 3],k = 2→False— every repeated value is exactly 3 apart, which exceedsk = 2.
Constraints
1 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^90 <= k <= 10^5
Both n and k can be 10^5, so an O(n·k) scan of each index’s neighborhood can hit 10^10 steps — the expected solution is linear.
Think about it first
Hint 1
You only care whether the value at indexi appeared anywhere in the previous k positions. What structure answers "have I seen this?" in O(1)?
Hint 2
Maintain a set holding exactly the values inside the lastk positions. As the window slides one step right, one value enters and (once the window is full) one value leaves.
Hint 3
For each indexi: if nums[i] is already in the set, return True; otherwise add it, and if the set now holds more than k values, remove nums[i - k]. Alternatively, store each value's last-seen index in a dict and compare distances.