Java Program to Find Duplicate Number in an Array

In this Java program, we will learn how to find the duplicate number in an array. We will use the

Java Program to Find Duplicate Number in an Array

We can find the duplicate number in an array by comparing each element with all other elements in the array. If we find any element that is equal to any other element in the array, then it is a duplicate number. We will use two nested loops to compare each element with all other elements in the array. If we find any element that is equal to any other element in the array, then it is a duplicate number.

public class FindDuplicateNumberInArray {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1};
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    System.out.println("Duplicate Number: " + arr[j]);
                }
            }
        }
    }
}
Output:
Duplicate Number: 1
Time Complexity: O(n2) - We are using two nested loops to compare each element with all other elements in the array.
Space Complexity: O(1) - We are not using any extra space.