304 North Cardinal St.
Dorchester Center, MA 02124

# Contains Duplicate II LeetCode Solution

## Problem – Contains Duplicate II

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`

### Contains Duplicate II LeetCode Solution in Java

``````public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(i > k) set.remove(nums[i-k-1]);
}
return false;
}
``````

### Contains Duplicate II LeetCode Solution in Python

``````def containsNearbyDuplicate(self, nums, k):
dic = {}
for i, v in enumerate(nums):
if v in dic and i - dic[v] <= k:
return True
dic[v] = i
return False
``````

### Contains Duplicate II LeetCode Solution in C++

``````class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_set<int> s;

if (k <= 0) return false;
if (k >= nums.size()) k = nums.size() - 1;

for (int i = 0; i < nums.size(); i++)
{
if (i > k) s.erase(nums[i - k - 1]);
if (s.find(nums[i]) != s.end()) return true;
s.insert(nums[i]);
}

return false;
}
};
``````
##### Contains Duplicate II LeetCode Solution Review:

In our experience, we suggest you solve this Contains Duplicate II LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Contains Duplicate II LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Contains Duplicate II LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions