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
First Unique Character ProblemInput: "leetcode" → Output: 2letecode01234567RepeatedRepeatedUnique!RepeatedUniqueUniqueUniqueRepeatedFirst unique character 't' found at index 2Return: 2
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
Asked in
Amazon 45 Google 35 Microsoft 28 Apple 20
125.0K Views
High Frequency
~15 min Avg. Time
4.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen