Leetcode 219. Contains Duplicate II
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 the absolute difference between i
and j
is at most k
.
nums
and the integer k
?
nums
can be any integer within the allowed range of integer values in C++.k
will be a non-negative integer less than or equal to the length of the array.nums
is empty or contains only one element?
false
in such cases.k
, return true
.false
.#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> index_map; // to store the latest index of each number
for (int i = 0; i < nums.size(); i++) {
if (index_map.find(nums[i]) != index_map.end()) {
if (i - index_map[nums[i]] <= k) {
return true;
}
}
index_map[nums[i]] = i; // update the index of the current number
}
return false;
}
};
The time complexity of this solution is O(n) where n
is the number of elements in the array nums
. This is because we are making a single pass through the array and performing constant-time operations (hash map insertions and lookups) for each element.
The space complexity is also O(n) in the worst-case scenario when all elements in nums
are unique, resulting in the hash map storing n
key-value pairs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?