How do you find the first character in a string that appears exactly once?
Two passes. The first builds a frequency table for the whole string. The second walks the string from the left and returns the first character whose count is one. The order of the second pass is the whole point: the first unique character is defined by position, not by count.
from collections import Counter
def first_unique_char(text):
counts = Counter(text)
for char in text:
if counts[char] == 1:
return char
return None
print(first_unique_char("leetcode"))
print(first_unique_char("aabb"))The outputs are the letter l and None. In leetcode the characters l, e, t, c, o, d all appear twice except for u, which appears once, and u is the only unique character. In aabb every character appears twice, so there is no answer.
The mechanism is that counting alone cannot tell you which unique character comes first. The counter tells you the l in leetcode is unique only after you have seen the whole string. Scanning the original order afterwards gives you the position. Trying to return from inside the counting loop is a common mistake, because at that moment you do not yet know whether the character will repeat later.
The trade-off to name is space against time. The count table is O of k space where k is the number of distinct characters, and the whole algorithm is linear in the length of the string. The alternative is to scan once and keep the first candidate plus a flag marking it as suspect, which uses O of 1 space but is fiddly, because when a candidate is invalidated you have to remember the next one that was never a candidate at all. The two-pass version is worth the table in every realistic case.