#387
First Unique Character in a String
Easy Frequency count
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Return the index of the first character that appears exactly once in the string, or -1.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: the first letter that appears exactly once.
Why this works: count all letters first, then scan in order for a count of 1.
Example: "loveleetcode"
counts: l2 o2 v1 e4 …first with count 1: 'v' at index 2
✦Hints open one at a time
Count every letter first.
Then scan again in order and return the first index whose count is 1.
↗Approach
Two passes: frequency array, then the first position with frequency 1.
</>Solution (Java)
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (char c : s.toCharArray()) count[c - 'a']++;
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i) - 'a'] == 1) return i;
}
return -1;
}
}
!Common mistake
Scanning the count array in alphabetical order — you need the first by position in the string.
Complexity
- Time: O(n).
- Space: O(26).
Topic: Strings
🎬 Episodes 16–20: video coming soon