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.
๐ Master Duplicate Detection in Java Arrays
Finding duplicate elements in an array is a common Java coding-round and interview problem. It tests your understanding of array traversal, hashing, and time–space trade-offs. Strengthen your array problem-solving skills by exploring these closely related Java programs and interview resources.
๐ง Java Coding Round Questions
Practice array and collection-based problems frequently asked in coding rounds.
๐ซ Remove Duplicates from Array
Learn how detected duplicates can be efficiently removed.
✅ Check if Array Is Sorted
Sorted arrays simplify duplicate detection logic.
๐ Reverse Array
Strengthen array traversal and index manipulation skills.
๐ฅ Second Largest Element in Array
Practice scanning arrays while tracking unique values.
๐ Sort Array Without Built-ins
Sorting is often used before or after duplicate detection.
๐ฆ Java Collections Interview Questions
Learn how HashSet and Map help detect duplicates efficiently.
๐ฏ Java Interview Questions (Freshers)
Common interview questions involving arrays and duplicates.
๐งช Advanced Java Programs (Real-World)
Apply duplicate detection logic in real-world Java scenarios.