First Unique Character in a String
Easy · Stack & Strings · Hash Table · String · Queue · Counting
Problem
Given a string s, find the first character that appears exactly once in it and return its index. If every character repeats, return -1.
Examples
Input: s = "swiss" Output: 1
's' repeats, so the first unique character is 'w' at index 1.
Input: s = "abab" Output: -1
Both letters appear twice.
Input: s = "z" Output: 0
The only character is unique.
Constraints
- 1 <= len(s) <= 10^5
- s contains only lowercase English letters
Approaches
- Baseline: look for a copy of each character — time O(n²), space O(1)
Follow-up
The characters arrive one at a time as a stream, and after each one you must report the first unique character so far. Keep the counts plus a queue of candidates in arrival order, and pop from the front while the front has repeated: each character enters and leaves the queue at most once.
Related problems
Start free on Cariara · Coding problems · System design studio