Nearby Duplicate
Given an array of integers arr of size n and a non-negative distance k. Determine whether two equal values occur at different indices no more than k positions apart.
Specifically, return "YES" if there are two distinct indices i and j in the array such that arr[i] == arr[j] and abs(i - j) <= k. Otherwise, print "NO".
You must track each value's most recent index in a hash table.
Example 1:
Input:
arr = [1, 2, 3, 1] k = 3
Output:
YES
Explanation:
arr[0] == arr[3] and abs(0 - 3) = 3, which is <= 3.
Example 2:
Input:
arr = [1, 2, 3, 1] k = 2
Output:
NO
Explanation:
arr[0] == arr[3], but abs(0 - 3) = 3, which is not <= 2.
Now Your Turn!
Pick the correct output for the given inputInput:
arr = [1, 2, 3, 1, 2, 3] k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 105
- 0 <= k <= 105
- -109 <= arr[i] <= 109