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.

Input: nums = [1,2,3,1], k = 3
Output: true
Input: nums = [1,0,1,1], k = 1
Output: true
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Constraints:

Contents

In this approach, we are going to apply sliding window technique, using two pointers left and right, find if there is any duplicate element found within the window size of k ( i.e. right - left).

Implementation steps:
import java.util.HashSet; public class ContainsDuplicatesII { static boolean containsNearbyDuplicate(int[] nums, int k) { int left = 0; int right = 0; HashSet<Integer> dups = new HashSet<>(); while(right < nums.length) { if(right-left > k) { dups.remove(nums[left]); left++; } if(dups.contains(nums[right])) { return true; } dups.add(nums[right]); right++; } return false; // if nothing found } public static void main(String[] args) { System.out.println(containsNearbyDuplicate(new int[]{1, 2, 3, 1}, 3)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of nums array.
Space complexity: O(k) for the HashSet that is used check duplicates, and at any given time it contains atmost k elements.

Above implementations source code can be found at GitHub link for Java code