Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Input: nums = [1,2,3,1], k = 3
Output: true
Input: nums = [1,0,1,1], k = 1
Output: true
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
The simplest approach to solve this problem is to check every pair of elements in the array. If two elements are the same and are within the given range k from each other, we return true. Otherwise, we continue checking all possible pairs.
n is the length of the array.Instead of checking each pair, we can use a sliding window of size k and a HashSet to track the elements within that window. As we slide the window through the array, we can keep checking if the current element already exists in the HashSet. If it does, it means we found a duplicate within the given range.
k, as it only keeps track of k elements at a time.A small optimization can be done over the HashSet approach by using a HashMap which stores the indices. By keeping track of indices, we can avoid unnecessary otherwise possible duplicates removal. This approach reduces operations to a bare minimum required for ensuring unique elements within the window.
n unique elements and their last seen indices.