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: 4
💡 Note: The first unique character is 't' at index 4. 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 in a String INPUT String s = "leetcode" l 0 e 1 e 2 t 3 c 4 o 5 d 6 e 7 Input Values s = "leetcode" Length: 8 characters ALGORITHM STEPS 1 Create Hash Map Count frequency of each char 2 First Pass Iterate string, fill map 3 Second Pass Find first char with count=1 4 Return Index Or -1 if not found Hash Map (char --> count) 'l': 1 'e': 3 't': 1 'c': 1 'o': 1 'd': 1 Red = repeating (count > 1) FINAL RESULT Scanning for first unique char: l cnt=1 e cnt=3 e cnt=3 t cnt=1 ... First Unique! OUTPUT 2 Index of 't' OK - Character 't' at idx 2 Key Insight: Using a hash map allows O(n) time complexity. First pass counts all characters, second pass finds the first character with count = 1. Space complexity is O(1) since max 26 letters. The hash approach is optimal: O(n) time, O(1) space for lowercase English letters. TutorialsPoint - First Unique Character in a String | Hash Map Approach
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