First Unique Character in a String

Easy

Topics
StringHash TableQueue

Given a string s, return the index of the first non-repeating character. If none exists, return -1.

Example 1

l0e1e2t3c4o5d6e7
repeatsfirst unique
The answer is the index of the first character that appears exactly once in the whole string — index 0 here. First means first by position, which is not the same as the first character you have not seen before.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "leetcode"
Output: 0

Example 2

l0o1v2e3l4e5e6t7c8o9d10e11
repeatsfirst unique
Input:  s = "loveleetcode"
Output: 2

Example 3

a0a1b2b3
repeats
Every character in the string appears more than once, so there is no unique one and the answer is -1.
Input:  s = "aabb"
Output: -1

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A character is the answer if it appears exactly once. Count every character first, then scan left to right for the first with a count of 1.

Approach

  1. Build a frequency map of all characters.
  2. Scan the string; return the index of the first character whose count is 1.
  3. If none, return -1.

Walkthrough

s = "loveleetcode"
counts: l:2 o:2 v:1 e:4 t:1 c:1 d:1
first count==1 while scanning -> index 2 (v)

Complexity

  • Time — O(n): two passes over the string.
  • Space — O(1): the count map is bounded by the 26-letter alphabet.

Common Pitfalls

  • Scan the string for the first count of 1, not the counter. A Counter preserves first-encounter order, which is not the same as position: on bcbabc the first unique character is a at index 3, but walking the counter finds a as its third key and reports 2.
  • Two passes is the point. One pass cannot know a character is unique until the whole string has been read.

Full Solution — all languages

class Solution:
    def firstUniqChar(self, s):
        from collections import Counter
        cnt = Counter(s)
        for i, c in enumerate(s):
            if cnt[c] == 1:
                return i
        return -1
SensAI
Beta
Tap the mic to stop voice mode