</>

Technology

Java Programs

Difficulty

Intermediate

Interview Question

Write a Java program to find duplicate elements in an array.

Answer

Find Duplicate Elements in an Array

Method 1: Nested Loop (Simple)

Java
public class FindDuplicates {
    public static void main(String[] args) {
        int arr[] = { 1, 2, 3, 4, 2, 7, 8, 8, 3 };

        System.out.println("Duplicate elements:");

        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    System.out.println(arr[j]);
                }
            }
        }
    }
}

Output

CODE
Duplicate elements:
2
3
8

Method 2: HashSet (Efficient — O(n))

Java
import java.util.HashSet;
import java.util.Set;

public class FindDuplicatesHashSet {
    public static void main(String[] args) {
        int arr[] = { 1, 2, 3, 4, 2, 7, 8, 8, 3 };
        Set<Integer> seen    = new HashSet<>();
        Set<Integer> duplicates = new HashSet<>();

        for (int num : arr) {
            if (!seen.add(num)) {         // add() returns false if already present
                duplicates.add(num);
            }
        }

        System.out.println("Duplicates: " + duplicates);  // {2, 3, 8}
    }
}

Method 3: Sort + Adjacent Compare

Java
import java.util.Arrays;

int arr[] = { 1, 2, 3, 4, 2, 7, 8, 8, 3 };
Arrays.sort(arr);  // [1, 2, 2, 3, 3, 4, 7, 8, 8]

System.out.print("Duplicates: ");
for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] == arr[i + 1]) {
        System.out.print(arr[i] + " ");
    }
}
// Output: Duplicates: 2 3 8

Count Frequency of Each Element

Java
import java.util.HashMap;
import java.util.Map;

int arr[] = { 1, 2, 3, 4, 2, 7, 8, 8, 3 };
Map<Integer, Integer> freq = new HashMap<>();

for (int num : arr) {
    freq.put(num, freq.getOrDefault(num, 0) + 1);
}

System.out.println("Frequency map: " + freq);
// {1=1, 2=2, 3=2, 4=1, 7=1, 8=2}

freq.entrySet().stream()
    .filter(e -> e.getValue() > 1)
    .forEach(e -> System.out.println(e.getKey() + " appears " + e.getValue() + " times"));

Automation Testing Relevance

Java
// Check for duplicate values in a dropdown
List<WebElement> options = driver.findElements(By.tagName("option"));
Set<String> seen = new HashSet<>();
for (WebElement opt : options) {
    if (!seen.add(opt.getText())) {
        System.out.println("Duplicate option found: " + opt.getText());
    }
}

Follow AutomateQA