Java - Finding Duplicate Elements

public class Duplicate_Elements {

    public static void main(String[] args) {

        // Example array with duplicates

        int[] arr = {3, 5, 7, 3, 8, 7, 2, 5};

 

        System.out.println("Duplicate elements in the array:");

        

        // Traverse the array

        for (int i = 0; i < arr.length - 1; i++) {

            for (int j = i + 1; j < arr.length; j++) {

                // If duplicate is found

                if (array[i] == array[j]) {

                    System.out.println(array[i]);

                    break;  // Avoid printing the same duplicate multiple times

                }

            }

        }

    }

}

 

Explanation of the Program

Nested loops

The outer loop (i) iterates through each element of the array.

The inner loop (j) begins at i + 1 and tests if any consecutive element matches the current one (array[i]).

If condition

If it finds a duplicate element (array[i] == array[j]), it prints it.

Break statement:

The break is used to cease checking whenever a duplicate of that element is identified, preventing the same duplicate from being printed several times.

 

Conclusion

While this method is not the most efficient in terms of time complexity, it does show how to locate duplicate elements with only arrays and nested loops. For smaller datasets or when memory is limited, this method can still be beneficial.