219. Contains Duplicate II ๐
Difficulty: Easy
- Tags: Array
, Hash Table
, Sliding Window
Problem Statement ๐
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.
Examples ๐
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
Constraints โ๏ธ
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
0 <= k <= 10^5
Solution ๐ก
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
.
Java Solution (Using HashMap)
Explanation of the Solution
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.
Time Complexity โณ
O(n): Each element is processed once.
Space Complexity ๐พ
O(min(n, k)): The size of the
HashMap
is limited byk
and the number of unique elements innums
.
You can find the full solution here.
Last updated