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;
}
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.
- Create an array to keep visited string characters
- If the array includes the current character then return that char
- That's the first repeated character
- Else add current character in the array created in point 1
- Return
null
if there is no duplicate character in the given string
- We create an empty array
duplicateEntry
- We iterate over characters
char
of given stringstr
- In each iteration, we check if the current character
char
is present in theduplicateEntry
- If it is present then we return that current character
char
. That's our first duplicate character in given stringstr
- If not then we add that current character
char
induplicateEntry
array - If we don't find any duplicate character in
duplicateEntry
array then we returnnull
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.