Coding Challenge - #3: Find Duplicate Values

Write a function findDuplicates(arr) that returns an array of values that appear more than once in the input array, each value listed only once, in the order they first repeat. For example, findDuplicates([1,2,3,2,4,1]) should return [2,1].

function findDuplicates(arr) {
  // your code here
}

Rules:

  • Plain JavaScript only, no libraries
  • Return values in order of first repeat, not first appearance
  • Each duplicate value should appear only once in the result
  • Solution should be about 3 to 10 lines

Post your solution as a reply. Answer goes up in about a day.

Here is my attempt:

function findDuplicates(arr) {
   let unique = new Set();
   let duplicates = new Set();
   for (let i = 0; i < arr.length; i++) {
         let current = arr[i];
         if (!unique.has(current)) {
              unique.add(current);
         } else {
              duplicates.add(current);
         }
   }
   return duplicates;
}

console.log(findDuplicates([1,2,3,2,4,1]));

Logged it, no verdict from me though. Answer drops later today, try not to stare at that return type too hard until then.

Your logic is solid-you’re tracking unique and duplicate values correctly.

The challenge asks for an array though, not a Set.

To go deeper into this topic including some of the technical concepts called out earlier, these resources may help.

Ok - now it returns an array!

function findDuplicates(arr) {
   let unique = new Set();
   let duplicates = new Set();
   
   for (let i = 0; i < arr.length; i++) {
         let current = arr[i];
         if (!unique.has(current)) {
              unique.add(current);
         } else {
              duplicates.add(current);
         }
   }
   
   // Convert the Set to an Array before returning
   return [...duplicates];
}

console.log(findDuplicates([1, 2, 3, 2, 4, 1]));

sets and spread, love it, tucked that guess away for later. answer drops later today so we’ll see how it holds up

Challenge solution: Track how many times each value has been seen with a Map, and push a value into the result array at the exact moment its count first becomes 2, giving the order of first repeat.

One way to do it:

function findDuplicates(arr) {
  const counts = new Map();
  const result = [];
  for (const val of arr) {
    const count = (counts.get(val) || 0) + 1;
    counts.set(val, count);
    if (count === 2) {
      result.push(val);
    }
  }
  return result;
}

Why:
Each element is counted as it is encountered, and a value is added to the result only once, exactly when its occurrence count transitions from 1 to 2, which naturally captures the order in which values first repeat. Using a Map avoids duplicate entries and keeps the logic O(n).


Got it: @kirupa :trophy:

First-answer leaderboard

  1. @kirupa - 3 (firsts) :trophy:
  2. @emmawalter5 - 1 (first)