First Unique Character in a String — LeetCode 387 Python Solution
EasyQueueHash TableStringCounting
- Problem
- #387
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(|\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.