Practice: First Unique
Count, then search.
Find the first character in a word that appears only once. In swiss, it's W. Pause and try. Hint. You might need to go through the word twice.

- The first character that appears once
- In 'swiss', it's w
- Two passes?
Count, then search
First pass, count every character with Counter. Second pass, go through the word in order, and return the first character with a count of one. Two passes is still O of N, because two N is just O of N. Run it. W for swiss, V for level, and none for AABB, where nothing is unique.
from collections import Counter
def first_unique(word):
counts = Counter(word)
for ch in word:
if counts[ch] == 1:
return ch
return None
for w in ["swiss", "level", "aabb"]:
print(w, "->", first_unique(w))swiss -> w level -> v aabb -> None
The counting pattern
Many problems follow this same shape. Count things with a dictionary in one pass, then use the counts in a second pass. Most frequent word, first unique item, checking for anagrams, and finding duplicates all work this way.
| key | value |
|---|---|
| Pass 1 | count with Counter |
| Pass 2 | use the counts |
| Total | still O(n) |
| Used for | uniques, anagrams, top k |
Summary
Count in one pass, then search in a second. It's simple, fast, and works for many problems. Next, a technique for scanning ranges of an array. The sliding window.
Key takeaways- Counter first
- Then scan in order
- O(n)