Coding Challenge Practice – Question 62

The task is to write a function that finds the first duplicate given a string that might contain duplicates.

The boilerplate code

function firstDuplicate(str) {
  // your code here
}

Declare a variable to keep track of every character that is seen

const seen = new Set()

As soon as a character that has been seen previously is reached, that is the first duplicate.

for (let char of str) {
    if (seen.has(char)) {
      return char;  
    }
    seen.add(char);
  }

If the end is reached and there is no repeat, return null.

The final code

function firstDuplicate(str) {
  // your code here
  const seen = new Set();

  for(let char of str) {
    if(seen.has(char)) {
      return char;
    }
    seen.add(char)
  }
  return null;
}

That’s all folks!

Similar Posts