← Hash Maps

Drill #24 — First non-repeating character

Easy Frequency Count Hash Maps

In plain English: Find the first character in a string that appears only once.

Two passes: first count all frequencies, then scan left-to-right for the first count of 1 — the scan order ensures 'first'.

Prompt

Find the index of the first character that appears only once.

Try to write it from scratch before scrolling down.

Solution

def first_unique(s):
    # first pass: count, second pass: find
    freq = {}
    for c in s:
        freq[c] = freq.get(c, 0) + 1
    for i, c in enumerate(s):
        if freq[c] == 1:
            return i
    return -1

# Test: first_unique("aabbcdd") == 4  (index of 'c')
O(n) time · O(k) space

Related Micro Drills

← Drill #23 Drill #25 →