Find the first un-repeated character in a string

It has to be at least O(n) because you don’t know if a character will be repeated until you’ve read all characters.

So you can iterate over the characters and append each character to a list the first time you see it, and separately keep a count of how many times you’ve seen it (in fact the only values that matter for the count is “0”, “1” or “more than 1”).

When you reach the end of the string you just have to find the first character in the list that has a count of exactly one.


Example code in Python:

def first_non_repeated_character(s):
    counts = defaultdict(int)
    l = []
    for c in s:
        counts[c] += 1
        if counts[c] == 1:
            l.append(c)

    for c in l:
        if counts[c] == 1:
            return c

    return None

This runs in O(n).

Leave a Comment