Return the elements that appear more than once (e.g. [1,2,2,3,4,4,4] -> [2,4]).
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.
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]Duplicate detection is core data validation — duplicate ids from an API, repeated rows after a migration.
The array holds a million integers in the range 1..n and memory is tight. Can you avoid the hash set?