Sollicitatievraag bij HCLTech

write a Java program to identify duplicate elements in a string array

Antwoord op sollicitatievraag

Anoniem

7 nov 2025

public class DuplicateStrings { public static void main(String[] args) { // Example string array String[] words = {"apple", "banana", "cherry", "apple", "date", "banana", "fig"}; // Create a HashSet to track unique words HashSet seen = new HashSet<>(); HashSet duplicates = new HashSet<>(); // Loop through the array for (String word : words) { // If the word is already in 'seen', it's a duplicate if (!seen.add(word)) { duplicates.add(word); } } // Display results if (duplicates.isEmpty()) { System.out.println("No duplicate elements found."); } else { System.out.println("Duplicate elements: " + duplicates); } } }