Hone logo
Hone
Problems

Finding the First Non-Repeated Character

This challenge asks you to implement a function that identifies the first character in a string that appears only once. This is a common problem in string manipulation and can be useful in scenarios like parsing data, analyzing text, or optimizing search algorithms where you need to quickly find unique elements.

Problem Description

You are tasked with writing a JavaScript function called firstNonRepeatedCharacter(str) that takes a string str as input and returns the first non-repeated character in the string. If all characters are repeated, or the string is empty, the function should return null.

Key Requirements:

  • The function must be case-sensitive (e.g., 'a' and 'A' are considered different characters).
  • The function should return the first non-repeated character encountered.
  • The function should handle empty strings and strings where all characters are repeated.

Expected Behavior:

The function should iterate through the input string, keeping track of the frequency of each character. It should then return the first character found with a frequency of 1.

Edge Cases to Consider:

  • Empty string: Should return null.
  • String with all repeated characters: Should return null.
  • String with mixed-case characters: Should treat uppercase and lowercase characters as distinct.
  • String with special characters and numbers: Should handle these correctly.

Examples

Example 1:

Input: "stress"
Output: "t"
Explanation: The character 't' appears only once in the string "stress".

Example 2:

Input: "aabbcc"
Output: null
Explanation: All characters in the string "aabbcc" are repeated.

Example 3:

Input: "aAbBcCdD"
Output: "a"
Explanation: The character 'a' appears only once, even though 'A' is also present.

Example 4:

Input: ""
Output: null
Explanation: The input string is empty.

Example 5:

Input: "abcabcbb"
Output: null
Explanation: All characters are repeated.

Constraints

  • The input string str will contain only alphanumeric characters and spaces.
  • The length of the input string str can be between 0 and 1000 characters (inclusive).
  • The function should have a time complexity of O(n), where n is the length of the string. While a nested loop solution might work, it will not satisfy this constraint.

Notes

Consider using a data structure (like a JavaScript object or Map) to efficiently store and update the character frequencies. Think about how to iterate through the string only once to achieve the desired time complexity. Remember to handle the edge cases gracefully.

Loading editor...
javascript