easyArrays & HashingPure DSA~14 min
Duplicate Within K Events
An event pipeline tolerates the same event ID reappearing, but a true duplicate within a short window of k events signals a retry storm worth flagging. Decide whether any value repeats within k positions of itself.
Problem
Given an array nums and an integer k, return true if there exist two indices i and j such that nums[i] == nums[j] and |i - j| ≤ k.
Input
An array nums of length n (1 ≤ n ≤ 10^5) and integer k (0 ≤ k ≤ n).
Output
A boolean — true if a near-duplicate exists within distance k.
Constraints
- 1 ≤ n ≤ 100,000
- 0 ≤ k ≤ n
- Values in [-10^9, 10^9]
Examples
Example 1
Input
nums = [1, 2, 3, 1], k = 3
Output
true
The two 1s are at indices 0 and 3, a distance of 3 which is ≤ k.
Example 2
Input
nums = [1, 2, 3, 1, 2], k = 1
Output
false
Each repeated value is 3 apart, exceeding k = 1.