```
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> val_pos; //value to position
for(int i = 0; i< nums.size(); i++)
{
if(val_pos.count(nums[i])) //repeat exist
{
if( (i - val_pos[nums[i]])<= k)
return true;
val_pos[nums[i]] = i;
}
val_pos[nums[i]] = i;
}
return false;
}
};
```

The basic idea is to check if the two equal elements are in the range k. If in the range, then return true, if not, update the hash map with the latest index of the number and continue.