Hiprup

How do you find duplicates in an array?

Identify values that appear more than once.

  • Set of seen — loop once, tracking seen values; if a value's already seen, it's a duplicate.

  • Frequency map — count occurrences, then keep values with a count above 1.

  • Quick check — comparing array length to a Set's size tells you if any duplicates exist.

Usual answer: the seen-set approach is O(n).

const arr = [1, 2, 3, 2, 4, 3, 5, 1];

// Method 1: Set — find duplicate values
function findDuplicates(arr) {
  const seen = new Set();
  const duplicates = new Set();
  for (const item of arr) {
    if (seen.has(item)) duplicates.add(item);
    else seen.add(item);
  }
  return [...duplicates];
}
console.log(findDuplicates(arr)); // [2, 3, 1]

// Method 2: filter + indexOf
const dupes = arr.filter((item, index) => arr.indexOf(item) !== index);
console.log([...new Set(dupes)]); // [2, 3, 1]

// Method 3: Map for frequency counting
function findDuplicatesMap(arr) {
  const freq = new Map();
  arr.forEach(item => freq.set(item, (freq.get(item) || 0) + 1));
  return [...freq.entries()].filter(([_, count]) => count > 1).map(([val]) => val);
}

// Check if array has ANY duplicates (boolean)
const hasDuplicates = arr => new Set(arr).size !== arr.length;
console.log(hasDuplicates([1, 2, 3]));       // false
console.log(hasDuplicates([1, 2, 2]));       // true

Set approach: tracks seen items, adds to duplicates if already seen. O(n) time. filter+indexOf: keeps items where the first occurrence is not at the current index.

Map counts frequencies, filters entries with count > 1. The hasDuplicates one-liner compares Set size to array length.

The Set approach (seen + duplicates) is the most efficient (O(n)). The hasDuplicates one-liner (new Set(arr).size !== arr.length) is a clean boolean check.

The filter+indexOf approach is O(n²) but concise. Show at least two approaches.

How do you find duplicates in an array? | Hiprup