Problem Statement
First Unique Character in a String
You are given a string s. Find the first character that shows up exactly once and return its index, meaning its position counting from 0. If every character repeats, return -1.
Signals to notice
Brute force first
For each character, count its occurrences in the entire string. Each character re-scans the whole string. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Two passes: first count all frequencies in a hash map, then scan left-to-right to find the first character with count 1 (26 letters max). The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on s="loveleetcode"
Pass 1 — build count by scanning all chars: count = {l:2, o:2, v:1, e:4, t:1, c:1, d:1}
Pass 2, i=0 c='l': count['l']=2 ≠ 1 → skip
i=1 c='o': count['o']=2 ≠ 1 → skip
i=2 c='v': count['v']=1 == 1 → first unique found
return 2What must stay true
The frequency map gives lookup for any character's count. The second left-to-right pass ensures we find the FIRST unique character by order of appearance. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
count = frequency_map(s) # pass 1: tally every char
for i, c in enumerate(s): # pass 2: left-to-right
if count[c] == 1:
return i # first char seen exactly once
return -1Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Returning the least frequent character instead of the first unique one. Order matters — you must scan left-to-right in the original string. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.