Data structures problem 6 of 30

First unique character

  • Data structures
  • Easy

Write first_unique(s) that returns the index of the first character that appears exactly once in s, or -1 if there is none.

first_unique("leetcode")       # 0
first_unique("loveleetcode")   # 2
first_unique("aabb")           # -1
Show hint

Two passes: one to count, one to find.

Show solution
from collections import Counter

def first_unique(s):
    counts = Counter(s)
    for i, ch in enumerate(s):
        if counts[ch] == 1:
            return i
    return -1

The first pass builds a frequency table; the second finds the earliest character with a count of 1. Two passes are still O(n), and the table holds at most one entry per distinct character.

Want a problem like this every day? See today's problem and keep a streak going.