Skip to content

Instantly share code, notes, and snippets.

@Islati
Created May 26, 2023 09:50
Show Gist options
  • Save Islati/6d6608956f23123e46530725b53a4c56 to your computer and use it in GitHub Desktop.
Save Islati/6d6608956f23123e46530725b53a4c56 to your computer and use it in GitHub Desktop.
Coding Challenge:: firstNonRepeatedCharacter
/*
Solution has been optimized for 0(n) speed
indexOf has a time complexity of O(n), which means that the loop
could potentially have a time complexity of O(n^2) in the worst case,
where n is the length of the input string.
To avoid this performance issue, we use a plain JavaScript object
instead of a Map to store the character count, and use a separate loop to
find the first non-repeated character
*/
function firstNonRepeated(s) {
const charCount = new Map();
let nonRepeatedChar = "";
for (const char of s) {
charCount.set(char, (charCount.get(char) || 0) + 1);
}
for (const char of s) {
if (charCount.get(char) === 1) {
nonRepeatedChar = char;
break;
}
}
return nonRepeatedChar;
}
// Test the function with the provided examples
console.log(firstNonRepeated("hello")); // Output: "h"
console.log(firstNonRepeated("aabcc")); // Output: "b"
console.log(firstNonRepeated("aabbcc")); // Output: ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment