219. Contains Duplicate II | LeetCode Solution

219. Contains Duplicate II | LeetCode Solution

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`.

Example 1:

```Input: nums = [1,2,3,1], k = 3
Output: true
```

Example 2:

```Input: nums = [1,0,1,1], k = 1
Output: true
```

Example 3:

```Input: nums = [1,2,3,1,2,3], k = 2
Output: false
```

Constraints:

• `1 <= nums.length <= 105`
• `-109 <= nums[i] <= 109`
• `0 <= k <= 105`

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int>mymap;
if(k==0)return false;
int st=0,n=nums.size();
int end=0;
while(end<=k && end<n){
// cout<<end<<" ";
auto it=mymap.find(nums[end]);
if(it!=mymap.end())return true;
else mymap[nums[end]]++;
end++;
}
cout<<end;
while(end<n){
auto it=mymap.find(nums[st]);
if(it!=mymap.end());
mymap.erase(it);
auto itt=mymap.find(nums[end]);
if(itt!=mymap.end())return true;
else mymap[nums[end]]++;
st++;
end++;
}
return false;
}
};