DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

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
}
Enter fullscreen mode Exit fullscreen mode

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

const seen = new Set()
Enter fullscreen mode Exit fullscreen mode

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);
  }
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)