Find Duplicates in an Array in Java Without Using Built-in Methods

Finding duplicate elements in an array is a common problem in coding interviews. In this post, we’ll learn how to find duplicates without using HashSet or any built-in collection framework.

🔍 Approach

We’ll use a nested loop to compare each element with every other element after it. If a match is found and hasn’t been printed before, we consider it a duplicate.

✅ Java Program


public class FindDuplicates {
    public static void main(String[] args) {
        int[] arr = {4, 2, 7, 2, 4, 9, 1, 4};
        boolean[] visited = new boolean[arr.length];

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

        for (int i = 0; i < arr.length; i++) {
            if (visited[i]) continue;
            boolean isDuplicate = false;

            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    isDuplicate = true;
                    visited[j] = true;
                }
            }

            if (isDuplicate) {
                System.out.println(arr[i]);
                visited[i] = true;
            }
        }
    }
}

🧠 Interview Tip

Try solving this with multiple approaches: brute force, using sorting, and using HashSet. Interviewers often ask for optimized solutions too.

✅ Output

Duplicate elements in the array:
4
2

📌 Conclusion

In this tutorial, we learned how to find duplicate elements in an array without using built-in Java methods. It's a good practice problem for building logic and understanding nested loops.