LeetCode #387: First Unique Character in a String
Given a string s, find the first non-repeating character and return its index. If it doesn't exist, return -1.
Approach: Two passes — first count all characters, then find the first with count 1.
💭 Challenge time! Now implement this yourself using the strategy above. The best way to learn is by doing! ⭐
Complexity: Time O(n), Space O(1) — at most 26 chars.
def firstUniqChar(s):
count = {}
# Pass 1: Count frequencies
for c in s:
count[c] = count.get(c, 0) + 1
# Pass 2: Find first with count == 1
for i, c in enumerate(s):
if count[c] == 1:
return i
return -1
firstUniqChar("leetcode")
0
firstUniqChar("loveleetcode")
2
firstUniqChar("aabb")
-1