First Unique Character in a String
Easy · Arrays & Hashing · Explanation and code example
Iteration
How it works
Since the string contains only lowercase letters, we can iterate through all 26 characters and find the first occurrence of each. If a character's first and last occurrence are the same index, it appears exactly once. We track the minimum such index across all characters.
Steps
- Initialize
resto the string lengthn. - For each character from
'a'to'z':- Find its first occurrence index using
indexOf(or equivalent). - Find its last occurrence index using
lastIndexOf. - If both indices are equal and the character exists, update
reswith the minimum.
- Find its first occurrence index using
- Return
resif it's less thann, otherwise return-1.
Complexity
- Time complexity:
O(26 * n)since we have at most26different characters. - Space complexity:
O(1)
Things to watch for
Returning the Character Instead of the Index
The problem asks for the index of the first unique character, not the character itself. A common mistake is returning the character or returning a 1-based index instead of a 0-based index. Always double-check what the problem is asking for and ensure your return type matches.
Iterating Over the Hash Map Instead of the String
When using a hash map to count frequencies, iterating over the map to find the first unique character loses the original order. Hash maps in most languages do not preserve insertion order. You must iterate over the original string in a second pass to find the first character with count equal to 1.
Python code example
class Solution:
def firstUniqChar(self, s: str) -> int:
res = n = len(s)
for ch in range(ord('a'), ord('z') + 1):
index = s.find(chr(ch))
if index != -1 and s.rfind(chr(ch)) == index:
res = min(res, index)
return -1 if res == n else res
C++ code example
class Solution {
public:
int firstUniqChar(string s) {
int res = s.size();
for (char ch = 'a'; ch <= 'z'; ch++) {
int firstIndex = s.find(ch);
if (firstIndex != string::npos && s.rfind(ch) == firstIndex) {
res = min(res, firstIndex);
}
}
return res == s.size() ? -1 : res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.