Ad

The algorithm works with constant complexity O(n), memory is limited to O(n)

Code
Diff
  • const firstNonRepeatingCharacter = (str) => {
        let stack = str.split('')
        let deletedChars = ''
        let result;
        
        while(stack.length > 0) {
          let current = stack.shift()
          
          if (!deletedChars.includes(current)) {
              if (!stack.includes(current)) {
                  result = current;
                  break;
              } else {
                  deletedChars += current;
              }
          }
        }
        
        return result || null;
    };
    • const firstNonRepeatingCharacter = (str) => {
    • for (let i = 0; i < str.length; i++) {
    • let seenDuplicate = false;
    • for (let j = 0; j < str.length; j++) {
    • if (str[i] === str[j] && i !== j) {
    • seenDuplicate = true;
    • break;
    • }
    • }
    • if (!seenDuplicate) {
    • return str[i];
    • }
    • let stack = str.split('')
    • let deletedChars = ''
    • let result;
    • while(stack.length > 0) {
    • let current = stack.shift()
    • if (!deletedChars.includes(current)) {
    • if (!stack.includes(current)) {
    • result = current;
    • break;
    • } else {
    • deletedChars += current;
    • }
    • }
    • }
    • return null; // return null if no unique character is found
    • return result || null;
    • };