LeetCode 387 · Hashing

First Unique Character in a String, explained with a picture

The first guest with a one-off ticket colour.

Hashing
▶ Watch it step by step

The problem

Find the position of the first character that appears only once, or −1.

Input:  "loveleetcode"
Output: 2   ("v")

Picture it

Picture a queue of people holding lettered tickets. First count how many of each letter there are. Then walk the queue from the front; the first person whose letter count is 1 is the answer.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Two passes: count, then scan. O(n).

Python solution

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

LeetCode adds the imports for you. To run this on your own machine, put this at the top: from collections import Counter

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.