Approach 1Optimal▶ Animated
Count, then scan
Count every letter, then return the first index whose count is 1 — or −1.
Two linear passes: the first builds frequencies, the second asks “is this the first singleton?”
Algorithm
- Count characters.
- Return the first index with count 1.
- If none, −1.
- Time
- O(n)
- Space
- O(σ)
class Solution: def firstUniqChar(self, s: str) -> int: count: dict[str, int] = {} for ch in s: count[ch] = count.get(ch, 0) + 1 for i, ch in enumerate(s): if count[ch] == 1: return i return -1