First Unique Character in a String — LeetCode 387 Python Solution

EasyQueueHash TableStringCounting
Problem
#387
Pattern
Stack
Reading time
2 min

The problem

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Python solution

Python
class Solution:
    def firstUniqChar(self, s: str) -> int:
        cnt = Counter(s)
        for i, c in enumerate(s):
            if cnt[c] == 1:
                return i
        return -1

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(|\Sigma|), where \Sigma is the character set auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 387. First Unique Character in a String is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 387. First Unique Character in a String?
LeetCode 387. First Unique Character in a String is rated Easy on LeetCode.
What is the time complexity of LeetCode 387. First Unique Character in a String?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 387. First Unique Character in a String?
The Python solution on this page uses O(|\Sigma|), where \Sigma is the character set auxiliary space.
What topics does LeetCode 387. First Unique Character in a String cover?
LeetCode 387. First Unique Character in a String is tagged Queue, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview