← Back to libraryQuestion 83 of 273
⌨️Java CodingIntermediate

Find Duplicate Elements in an Array

📌 Definition:

Return the elements that appear more than once (e.g. [1,2,2,3,4,4,4] -> [2,4]).

📖 Detailed Explanation:

Track seen elements in a hash set; if adding an element reports it was already present, it is a duplicate (collect it in a result set to avoid reporting twice). O(n) time, O(n) space. Sorting then scanning neighbors is O(n log n) with O(1) extra space.

💻 Solutions:
public static Set<Integer> findDuplicates(int[] a) {
    Set<Integer> seen = new HashSet<>(), dups = new LinkedHashSet<>();
    for (int x : a) if (!seen.add(x)) dups.add(x);
    return dups;
}
function findDuplicates(a) {
  const seen = new Set(), dups = new Set();
  for (const x of a) seen.has(x) ? dups.add(x) : seen.add(x);
  return [...dups];
}
from collections import Counter

def find_duplicates(a):
    return [x for x, c in Counter(a).items() if c > 1]
🔑 Key Points:
  • Set membership: already present -> duplicate
  • Collect duplicates in a set to avoid repeats
  • Frequency map also gives counts
  • Sort + scan is the O(1)-space alternative
🌍 Real-World Example:

Duplicate detection is core data validation — duplicate ids from an API, repeated rows after a migration.

🎯 Scenario-Based Interview Question:

The array holds a million integers in the range 1..n and memory is tight. Can you avoid the hash set?