-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathprodg.cpp
23 lines (22 loc) · 903 Bytes
/
prodg.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> mp;
int n = nums.size();
for(int i=0; i<n; i++)
{
// mp.count() will tell whatever ith index that I want, have I seen it before?
if(mp.count(nums[i]))
{
// if I have already seen this number, then check for condition abs(i - j) <= k
if(abs(i-mp[nums[i]])<=k)
return true;
}
// if I have not seen this number before, insert the number with its position in the map
// and if the number is already present in the map, then update the position of that number
mp[nums[i]] = i;
}
// after the complete traversal, if we don't find a pair to satisfy the condition, return false
return false;
}
};