Site icon

Check if array contains duplicate elements using java (example)

Problem Statement:

Solution: Check if array contains duplicate elements

Algorithms – find duplicates in an array using java

1.) First Iteration of array:

Fig 1: First iteration of array

2.) Second Iteration of array:

Fig 2: Second iteration of array

3.) Third Iteration of array:

Fig 3: Third iteration of array

4.) Similarly, In Fourth iteration will result in Fig 4.

Fig 4: Fourth iteration of array

5.) Fifth Iteration of array: 

Fig 5: Fifth iteration of array

Program – Check if array contains duplicate elements in java

package org.learn.arrays;

public class CheckDuplicates {

	public static void main(String[] args) {
		int[] array = { 2, 1, 5, 4, 2, 3, 1 };
		isDuplicate(array);

		array = new int[] { 2, 1, 3, 0 };
		isDuplicate(array);
	}

	private static void isDuplicate(int[] numbers) {
		
		for (int index = 0; index < numbers.length; index++) {
			int absIndex = Math.abs(numbers[index]);
			
			if (numbers[absIndex] < 0) {
				// We have already seen this number
				System.out.println("1. Duplicate number exist in array at index : " + index);
				return;

			} else { // We are seeing this number for first time
				numbers[absIndex] = -numbers[absIndex];
			}
		}
		System.out.println("2. No duplicate element exists in an array");
		return;
	}
}

Output – Check if array contains duplicate elements in java

1. Duplicate number exist in array at index : 4
2. No duplicate element exists in an array
Exit mobile version