Learn-dsa..in 30 days!



























CC-11 : : Find first number that has duplicate within n distance.

Description:

Given an array of integers arr with duplicates, find the first integer with a duplicate within n distance.

Test cases and expected outputs:

Input Parameters Expected outputs
arr1[]={ 1,4,7,3,5,8,3,7,9,3,4}; n=5 First repeating number within 5 distance is 3.
arr2[]={ 3,7,4,5,8,9,2,0,3,5,7}; n=5 There is no number that repeats with 5 distance.

Pseudocode:

The java method should accept following input parameters: arr (int array), n (integer).
Initialize a variable set of type HashSet to hold the input elements of arr.
Using a for loop iterate through arr, using idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
If set contains arr[idx], we have found the first integer with a duplicate within n distance, so return arr[Idx] from the program.
If above is not true, add arr[idx] to set.
If (idx >=n) then remove the integer at arr[idx-n] from set, this will mean all those integer elements of arr that do not have duplicate within n distance are removed. Only integers with distance < n remain in the set, this allows us to find duplicates within n distance.
At completion of above loop, if we have not found a duplicate integer within n distance, this means none of the integers within the array have duplicate within n digits. Return Integer.MIN_VALUE indicating the fact that we have not found any integer with duplicate within n distance in arr.

Code:

public int setArrayFindDuplicateWithinNDistance(int[] arr, int n) {
	HashSet<Integer> set=new HashSet<Integer>();
	for (int idx=0; idx < arr.length; idx++) {
		if (set.contains(arr[idx])) {
			return arr[idx];
		}
		set.add(arr[idx]);
		if (idx >= n) {
			set.remove(arr[idx-n]);
		}
	}	
	return Integer.MIN_VALUE;
}

Click here to download and run code and test cases !