# LeetCode – Contains Duplicate II (Java)

Given an array of integers and an integer k, return true if and only if there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

Java Solution 1

 public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap map = new HashMap(); int min = Integer.MAX_VALUE;   for(int i=0; i

Java Solution 2 - Simplified

 public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap map = new HashMap();   for(int i=0; i
 public boolean containsNearbyDuplicate(int[] nums, int k) { if(nums==null || nums.length<2 || k==0) return false;   int i=0;   HashSet set = new HashSet();   for(int j=0; j=k+1){ set.remove(nums[i++]); } }   return false; }
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>
• Sumedha Prathipati

Hi ,
We can do this without the set , right?!

• ricky

I think if you use two pointers from front and end. then you can do this in O(n).

• Vasyl Grygoryev

You are right. My code for this solution:

public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet set = new HashSet();

for (int i = 0; i = k)
set.remove(nums[i - k]);
}

return false;
}

• We can maintain a queue and hashset which only maintain current k elements. But this takes O(k) space.

• Cole Thatcher

Is there a way to do this O(n) time and O(1) space though? I’m just thinking how would we go about proving that there isn’t?