DSA Factory
Free Strings lessonsStrings · Stage 1 · Counting characters · Step 3

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.

First walk: just count.
s = "loveleetcode"
l
0
o
1
v
2
e
3
l
4
e
5
e
6
t
7
c
8
o
9
d
10
e
11
i
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.

Move 1 of 4

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.

Second walk: the first character counted once.
Walk the string: not the boxes, or you lose the order.
In code
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 -1
Quick check

In "aabcb", where is the first letter that appears only once?

  1. ABox 3
  2. BBox 2
  3. CNowhere: −1
Show the answer

Box 3. a appears twice, b twice, c once, and c is in box 3.

Your problem

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.

Example
s = "loveleetcode" → 2

0 ≤ length ≤ 1,000,000 · only a to z

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve