Created
December 25, 2022 05:30
-
-
Save thmain/2520f28f8df2fa9c6b55179dc5271316 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function findFirstUniqueCharacter( inputString ) { | |
let freqCounter = []; | |
// The issue using Map data structure is during the retrival. As it does not gaurantee the keys will be retrived in the same order as they were inserted | |
// Hence, we use an array of frequency counter. But in this array keys are found using the ascii values of the character. | |
inputString.split('').forEach(ch => { | |
if (!freqCounter[ch]) | |
freqCounter[ch] = 1; | |
else | |
freqCounter[ch]++; | |
}); | |
// Observe this array. It's kinda Map only. | |
console.log(freqCounter); | |
for (let i = 0; i < inputString.length - 1; i++) { | |
let ch = inputString[i]; | |
if (freqCounter[ch] == 1) | |
return ch; | |
} | |
return 'No Unique Character Found'; | |
} | |
console.log(findFirstUniqueCharacter('foobar')); // f | |
console.log(findFirstUniqueCharacter('aabbccdef')); // d | |
console.log(findFirstUniqueCharacter('aabbcc')); // 'No Unique Character Found' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment