🎉 One-stop destination for all your technical interview Preparation 🎉
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.
abs(i-j) <= k
.abs(i-j) <= k
.return true
else give the index of the number to the map.return false
if there is no duplicate in the range.class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
int n = nums.size();
unordered_map<int, int> mp;
for (int i = 0; i < n; i++) {
if (mp.count(nums[i]) && i - mp[nums[i]] <= k)
return true;
mp[nums[i]] = i;
}
return false;
}
};
O(k)
.class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
int n = nums.size();
unordered_set<int> st;
for (int i = 0; i < n; i++) {
if (st.count(nums[i])) {
return true;
}
st.insert(nums[i]);
if (st.size() > k) {
st.erase(nums[i - k]);
}
}
return false;
}
};