219. Contains Duplicate II ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: Array
, Hash Table
, Sliding Window
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]
abs(i - j) <= k
Return false
otherwise.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
0 <= k <= 10^5
To solve this problem efficiently, a HashMap
can be used to store the last index of each number as we iterate through the array. This allows us to quickly check if the difference between the current index and the stored index is less than or equal to k
.
HashMap for Index Tracking:
Use a HashMap
to store the last index where each number appears.
Check if the current number exists in the map, and if the index difference is less than or equal to k
.
Update the Map:
Regardless of the result, update the map with the current index of the number.
Early Exit:
If a valid pair is found, return true
.
Otherwise, continue iterating.
O(n): Each element is processed once.
O(min(n, k)): The size of the HashMap
is limited by k
and the number of unique elements in nums
.
You can find the full solution .