Count first, then look
Find the first character that appears only once, in two passes. About 7 minutes.
You can't decide on the first read
Find the first letter in "loveleetcode" that appears only once. When you reach the first l, can you say it's unique? No: another l might turn up later, and in fact one does.
So don't try to decide as you go. On the first walk, just count every letter. Nothing else.
- counts
- l:2 o:2 v:1 e:4 t:1 c:1 d:1
At the first 'l' we can't tell if another 'l' comes later. So the first walk only counts.
Then walk again and ask
Now walk the string a second time from the start. For each character, look up its count. The first one with a count of 1 is your answer. If none has a count of 1, return −1.
Walk the string, not the 26 boxes: the boxes are in alphabetical order, so they'd give you the alphabetically first unique letter, not the first one in the string.
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
for i, ch in enumerate(s):
if counts[ch] == 1:
return i
return -1In "aabcb", where is the first letter that appears only once?
- ABox 3
- BBox 2
- CNowhere: −1
Show the answer
Box 3. a appears twice, b twice, c once, and c is in box 3.
First letter that appears once
You get a string of lowercase letters. Return the position of the first character that appears exactly once in the whole string, or −1 if there isn't one.
s = "loveleetcode" → 2
0 ≤ length ≤ 1,000,000 · only a to z