# Check for duplicate elements within a given range k in an array

Given an array A with length n, the task is to find duplicates within a given range k in the array. For example let's assume given array is {1, 3, 4, 5, 6, 3} and k = 4 than the duplicate is 3, but if k = 3 there is no duplicate because two 3s are not in the range of k=3.

Input: {1, 3, 4, 5, 6, 3}, k=4
Output: 3

Input: {1, 3, 4, 5, 6, 3}, k=2
Output: -1

We can solve this problem in O(n) time using O(n) extra space, the idea is to maintain a sliding window of size k, and check if any element in that window is repeated, we will slide the window one element at a time by adding next element and removing i-k th element.

```package com.cd.array;

import java.util.Set;

public class FindDuplicateInRange {

private static int arr1[] = {1, 3, 4, 5, 6, 3};
private static int k1 = 4;

private static int arr2[] = {1, 3, 4, 5, 6, 3};
private static int k2 = 2;

private static boolean isDuplicate(int[] arr, int k) {

for (int i = 0; i < arr.length; i++) {
if (window.contains(arr[i]))
return true;

if (i - k >= 0)
window.remove(arr[i - k]);

}

return false;

}

public static void main(String[] args) {
System.out.println("Is Duplicate: "+isDuplicate(arr1, k1));
System.out.println("Is Duplicate: "+isDuplicate(arr2, k2));

}

}
```
Output: The output of the above example will look something like this:

```Is Duplicate: true
Is Duplicate: false
```