Find First Non-Repeating Character
function findFirstNonRepeatingChar(str) { // Handle empty or null string edge cases if (!str || str.length === 0) { return null; } const charCounts = new Map(); // First pass: Count character frequencies for (let i = 0; i < str.length; i++) { const char = str[i]; charCounts.set(c...
This algorithm finds the first character in a given string that appears only once. It iterates through the string twice: first to count the frequency of each character using a map, and then to find the first character wh...
The `findFirstNonRepeatingChar` function takes a string `str` as input. It first checks for edge cases like an empty or null string, returning `null` if either is true. A `Map` named `charCounts` is used to store the frequency of each character. The first loop iterates through the string, incrementing the count for each character in the map. The second loop iterates through the string again. For each character, it checks its count in `charCounts`. If the count is 1, that character is returned as it's the first non-repeating one encountered. If the loop completes without finding such a character, `null` is returned. The time complexity is O(n) because the string is traversed twice, and map operations (get/set) are O(1) on average. The space complexity is O(k), where k is the number of unique characters in the string, due to the map storage.
function findFirstNonRepeatingChar(string): if string is empty or null: return null create a map called charCounts for each character in string: increment count for character in charCounts for each character in string: i...