Skip to content

Instantly share code, notes, and snippets.

@thmain
Created December 25, 2022 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/2520f28f8df2fa9c6b55179dc5271316 to your computer and use it in GitHub Desktop.
Save thmain/2520f28f8df2fa9c6b55179dc5271316 to your computer and use it in GitHub Desktop.
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