We use a hash map (or fixed-size array) to count the frequency of each character. Then, we re-traverse the string to find the first character with a frequency of 1.
- Count character frequencies in
susing aCounter. - Iterate through
susing its indexi. - If
count[s[i]] == 1, returni. - If loop finishes, return -1.
- Time Complexity: O(N).
- Space Complexity: O(1) (since the alphabet size is constant).
from collections import Counter
def first_uniq_char(s):
counts = Counter(s)
for i, char in enumerate(s):
if counts[char] == 1:
return i
return -1