Find duplicate numbers in an array

Walk the array once with a Set of seen values: when a value is already in seen, it is a duplicate; collecting duplicates in a second Set gives each one once, in O(n) time and O(n) space.

Approaches compared

ApproachTimeSpaceNotes
Nested loopsO(n²)O(1)Simple, too slow for large inputs
Sort, then compare neighboursO(n log n)O(1)-O(n)Mutates or copies the array
Set of seen valuesO(n)O(n)Best general answer
Map of countsO(n)O(n)Also tells you how many times
filter + indexOfO(n²)O(n)Short but slow

Variants interviewers ask

  • Return each duplicate once ([1,2,2,2,3,3] → [2,3]): use a second Set.
  • Return all extra occurrences: push every time you see a value again.
  • Count occurrences: Map of value → count, then filter counts > 1.
  • First duplicate: return as soon as you hit one.
  • Values in range 1..n with O(1) extra space (LeetCode "Find All Duplicates"): mark visited indexes by negating arr[Math.abs(x) - 1]; mention it mutates the input.
  • Objects: compare by a key (id), not by reference.

Edge cases

Empty array, no duplicates, NaN (a Set treats NaN as equal to itself, indexOf does not), and 0 vs -0 (treated as equal by Set).

Code example

js
1function findDuplicates(arr) {
2 const seen = new Set();
3 const dupes = new Set();
4 for (const value of arr) {
5 if (seen.has(value)) dupes.add(value);
6 else seen.add(value);
7 }
8 return [...dupes];
9}
10
11function countOccurrences(arr) {
12 const counts = new Map();
13 for (const v of arr) counts.set(v, (counts.get(v) ?? 0) + 1);
14 return [...counts].filter(([, n]) => n > 1).map(([value, n]) => ({ value, n }));
15}
16
17// O(1) extra space when values are in 1..n (mutates a copy here)
18function findDuplicatesInRange(input) {
19 const nums = [...input];
20 const out = [];
21 for (const x of nums) {
22 const i = Math.abs(x) - 1;
23 if (nums[i] < 0) out.push(Math.abs(x));
24 else nums[i] = -nums[i];
25 }
26 return out;
27}
28
29console.log(findDuplicates([1, 2, 3, 2, 4, 3, 3, 5])); // [2, 3]
30console.log(countOccurrences([1, 2, 3, 2, 4, 3, 3, 5])); // [{ value: 2, n: 2 }, { value: 3, n: 3 }]
31console.log(findDuplicatesInRange([4, 3, 2, 7, 8, 2, 3, 1])); // [2, 3]
32console.log(findDuplicates([NaN, NaN, 0, -0])); // [NaN, 0]
33console.log(findDuplicates([])); // []
34
35// Objects: compare by key
36const users = [{ id: 1 }, { id: 2 }, { id: 1 }];
37console.log(findDuplicates(users.map((u) => u.id))); // [1]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app