```
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int size = nums.size();
int maxElements = k + 1;
// the difference between first and last element is at most k
if (size <= maxElements)
{
set<int> s(nums.begin(), nums.end());
return s.size() != size;
}
set<int> s(nums.begin(), nums.begin() + maxElements);
for (int i = maxElements; i < size; i++)
{
if (s.size() != maxElements)
return true;
s.erase(nums[i - maxElements]);
s.insert(nums[i]);
}
return s.size() != maxElements;
}
};
```

- Using a set to determine if any element repeats.
- For example, nums = { 1, 2, 3, 1, 3 } and k = 2
- Add all elements with index <= k to set s = { 1, 2, 3 }, and start for loop from k + 1 to the end of nums
- erase num[0] from set s and insert num[k + 1] to s, s = { 2, 3, 1 }
- erase num[1] from set s and insert num[k + 2] to s, s = { 3, 1 }
- If the size of set s is less than k + 1 at any step, it indicates duplicate items.