First Unique Character in a String - Problem
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
A non-repeating character appears exactly once in the string.
Input & Output
Example 1 — Basic Case
$
Input:
s = "leetcode"
›
Output:
2
💡 Note:
The first unique character is 't' at index 2. Characters 'l' and 'e' appear multiple times.
Example 2 — No Unique Character
$
Input:
s = "loveleetcode"
›
Output:
2
💡 Note:
The first unique character is 'v' at index 2.
Example 3 — All Characters Repeated
$
Input:
s = "aabb"
›
Output:
-1
💡 Note:
All characters appear more than once, so return -1.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of only lowercase English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with some repeated characters
2
Process
Find first character that appears exactly once
3
Output
Return index of that character, or -1 if none exists
Key Takeaway
🎯 Key Insight: Use frequency counting to efficiently identify unique characters in linear time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code