Write a function to find the first non-repeated character in a string.

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer

Logic/Approach:

1. Use a Map or an object to store the frequency of each character.

2. Iterate through the string once to populate the frequency map.

3. Iterate through the string a second time. For each character, check its count in the map. The first character with a count of 1 is the answer.

function firstNonRepeatedChar(str) {
  const charCount = new Map();

  // Count character frequencies
  for (const char of str) {
    charCount.set(char, (charCount.get(char) || 0) + 1);
  }

  // Find the first character with a count of 1
  for (const char of str) {
    if (charCount.get(char) === 1) {
      return char;
    }
  }

  return null; // Or an appropriate indicator if no non-repeated char is found
}

console.log(firstNonRepeatedChar("leetcode")); // "l"
console.log(firstNonRepeatedChar("stress")); // "t"
console.log(firstNonRepeatedChar("aabbcc")); // null