Skip to content

Latest commit

 

History

History
49 lines (38 loc) · 1.77 KB

File metadata and controls

49 lines (38 loc) · 1.77 KB

Solution

Submission link - https://bigfrontend.dev/problem/find-the-first-duplicate-character-in-a-string/discuss/680

/**
 * @param {string} str
 * @return {string | null}
 */
function firstDuplicate(str) {

  const duplicateEntry = []; // store string chars to find first duplicate

  for(let char of str) { 
    if(duplicateEntry.includes(char)) { // if the 'char' is already present means we have duplicate
      return char; // return the char, this will make sure we have first duplicate letter
    } else {
      duplicateEntry.push(char); // if 'char' is not present then add it
    }
  }
  return null;
}

Short story

I felt like this was simple. Though I'm not sure if there is another way to optimize it.
This is the first solution that came to my mind.

Algorithm

  1. Create an array to keep visited string characters
  2. If the array includes the current character then return that char
  3. That's the first repeated character
  4. Else add current character in the array created in point 1
  5. Return null if there is no duplicate character in the given string

Code overview

  1. We create an empty array duplicateEntry
  2. We iterate over characters char of given string str
  3. In each iteration, we check if the current character char is present in the duplicateEntry
  4. If it is present then we return that current character char. That's our first duplicate character in given string str
  5. If not then we add that current character char in duplicateEntry array
  6. If we don't find any duplicate character in duplicateEntry array then we return null

That's it. Simple.


I'm excited to improve the solution and code walkthrough. Feel free to drop a comment, or send a PR or send memes @knowkalpesh.