Skip to content
LEETFLIX

First Unique Character in a String

Solve on LeetCode

Easy · first unique char. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 387. First Unique Character in a String. The copyrighted prompt is on LeetCode. This page is a working first unique char for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

s =
leetcode

Output

0

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Count, then scan

Count every letter, then return the first index whose count is 1 — or −1.

Two linear passes: the first builds frequencies, the second asks “is this the first singleton?”

Algorithm

  1. Count characters.
  2. Return the first index with count 1.
  3. If none, −1.
Time
O(n)
Space
O(σ)
Solution.py
class Solution:    def firstUniqChar(self, s: str) -> int:        count: dict[str, int] = {}        for ch in s:            count[ch] = count.get(ch, 0) + 1        for i, ch in enumerate(s):            if count[ch] == 1:                return i        return -1
Watch this run

03

Interactive walkthrough

Playing “Count, then scan”. Edit the input, hit Run, then scrub.

Approach: Count, then scan

Loading animation…