First Unique Character in a String
You're given a string s of lowercase English letters. Find the first character, reading left to right, that appears exactly once in the whole string, and return its 0-based index. If every character appears more than once, return -1.
Examples
s = "leetcode" returns 0
The "l" at index 0 appears nowhere else, so it's the first unique character.
s = "loveleetcode" returns 2
"l" and "o" both appear twice, so indices 0 and 1 are out. The "v" at index 2 appears only once.
s = "aabb" returns -1
Both "a" and "b" appear twice, so no character is unique.
Constraints
- 1 <= s.length <= 10^5
- s consists of only lowercase English letters.
Hints
You can't tell whether a character is unique until you've seen the whole string. What could you gather first?
Count each character's frequency with a hash map or a 26-slot array, then scan the string a second time.
Pass 1: increment count[c] for every character. Pass 2: walk s from index 0 and return the first i where count[s[i]] == 1. Return -1 if the loop ends.
Drill This: Your Approach First
Approach
A character is unique only if it appears once in the whole string, so you can't decide during the first read. First count every letter in an array of 26 slots. Then walk s again from the left and return the first index whose letter has count 1, or -1 if none does. The count array has a fixed size, so extra space is constant.
Time
O(n)
Space
O(1)
Pitfall
Solutions
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i) - 'a'] == 1) return i;
}
return -1;
}
}class Solution:
def firstUniqChar(self, s: str) -> int:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
for i, c in enumerate(s):
if count[ord(c) - ord('a')] == 1:
return i
return -1