DSA problem
First Unique Character in a String
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
A character is considered non-repeating if it appears exactly once in the entire string. The answer must be the index of the leftmost such character.
The natural approach uses a hash map (or fixed-size array since the input is lowercase letters) to count how often each character occurs. After counting, a second scan of the string from left to right finds the first character whose count is exactly one.
Examples
Example 1
Input:
s = "leetcode"Output:
0Explanation: The character "l" at index 0 appears only once and is the first such character, so the answer is 0.
Example 2
Input:
s = "loveleetcode"Output:
2Explanation: The characters "l" and "o" both repeat. The first non-repeating character is "v" at index 2.
Example 3
Input:
s = "aabb"Output:
-1Explanation: Every character repeats, so there is no non-repeating character and the result is -1.
Constraints
- 1 <= s.length <= 10^5
- s consists of only lowercase English letters.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.