```
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (nums.empty() || k==0) return false;
unordered_map<int,int> mymap; //num, index
for (int i=1; i < nums.size()+1; i++) //we increment i, since the default for a key is zero
{
int x = nums[i-1];
if (mymap[x])
{
if (i-mymap[x] <= k)
return true;
else
mymap[x] = i;
}
else
mymap[x]=i;
}
return false;
}
```