How do you find the first character in a string that appears exactly once?
You count how many times each character appears, and then you walk through the text and take the first one that appears exactly once.
from collections import Counter
def first_unique_char(text):
counts = Counter(text)
for char in text:
if counts[char] == 1:
return char
return None
So why does it need two passes? Because the count is not enough on its own. The first character might appear three times, and the last one might appear once, and you cannot tell which is which until you have counted everything. So the first pass counts and the second pass finds the earliest character with a count of one.
And the complexity is O of n for the time, because you go through the text twice, and O of k for the space, where k is the number of different characters.
The next two questions in this topic show a version with a plain dictionary and a version that works on a stream.