# Easy and clear solution by using HashMap (JAVA)

• ``````public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
//check to avoid nullpointexception
if(nums == null){
return false;
}
Map<Integer,Integer> check = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i ++){
if(check.containsKey(nums[i])){
if( i - check.get(nums[i]) <= k){
return true;
}
}
check.put(nums[i], i);
}
return false;
}
}``````

• Same idea here. The only difference is to check length of array and k value at first.

``````public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || nums.length < 2 || k <= 0) return false;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]) && (i - map.get(nums[i])) <= k) return true;
map.put(nums[i], i);
}
return false;
}
}``````

• You are not considering the condition nums[i] = nums[j]

• Sorry, but could your please give an example input that you think the code not handled.

• he compare to nums[i] = nums[j] here:
``` if(check.containsKey(nums[i])) ```

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.