First Unique Character in a String - Problem
You are given a string s consisting of lowercase English letters. Your task is to find the first character that appears exactly once in the string and return its index position.
If no such unique character exists, return -1.
Example: In the string "leetcode", the character 'l' appears once at index 0, but 'e' appears multiple times. The first unique character is 't' at index 2.
This is a classic string processing problem that tests your ability to efficiently track character frequencies and find the optimal solution using hash tables.
Input & Output
example_1.py โ Basic case with unique character
$
Input:
s = "leetcode"
โบ
Output:
0
๐ก Note:
The character 'l' appears only once in the string at index 0, making it the first unique character.
example_2.py โ First unique not at beginning
$
Input:
s = "loveleetcode"
โบ
Output:
2
๐ก Note:
The characters 'l', 'o', and 'e' appear multiple times. The first character that appears exactly once is 'v' at index 2.
example_3.py โ No unique characters
$
Input:
s = "aabb"
โบ
Output:
-1
๐ก Note:
All characters appear more than once, so there is no unique character. Return -1.
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Queue
Walk through once and record how many times each badge number appears
2
Find the First Unique
Walk through again from the front, checking your records to find the first person with a unique badge
3
Report Position
Return the position of that person, or -1 if everyone has duplicate badges
Key Takeaway
๐ฏ Key Insight: By building a frequency map first, we can efficiently identify unique characters without redundant counting, making this a classic two-pass optimization pattern.
Time & Space Complexity
Time Complexity
O(n)
Two passes through the string, O(n) + O(n) = O(n)
โ Linear Growth
Space Complexity
O(k)
Hash table stores at most k unique characters (26 for lowercase letters)
โ Linear Space
Constraints
- 1 โค s.length โค 105
- s consists of only lowercase English letters
- The string is guaranteed to be non-empty
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code