Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
- The string
sconsists of only lowercase English letters.
Example 1:
Input: s = "leetcode"
Output: 0
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
Solution
The problem asks for the index of the first character that appears only once in the string.
- Frequency Counting: A common approach for character frequency problems is to use a hash map (or an array of size 26 for lowercase English letters) to store the count of each character.
- First Pass: Iterate through the string once to populate the frequency map. For each character, increment its count.
- Second Pass: Iterate through the string a second time. For each character at the current index, check its count in the frequency map.
- If the count is
1, this character is the first unique character. Return its current index.
- If the count is
- No Unique Character: If the loop completes without finding any character with a count of
1, it means no unique character exists. In this case, return-1.
from collections import Counter
class Solution:
def firstUniqChar(self, s: str) -> int:
# Step 1: Count character frequencies
# Counter creates a hash map (dictionary) of char -> count
char_counts = Counter(s)
# Step 2: Iterate through the string to find the first character
# with a count of 1
for i, char in enumerate(s):
if char_counts[char] == 1:
return i
# Step 3: If no unique character is found, return -1
return -1