Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
Example 1:
Input: s = "leetcode"
Output: 0
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
-1
.10^5
.To solve this problem efficiently, we can:
1
in the dictionary.def firstUniqChar(s: str) -> int:
# Step 1: Count the occurrences of each character
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# Step 2: Find the index of the first unique character
for index, char in enumerate(s):
if char_count[char] == 1:
return index
# Return -1 if there is no unique character
return -1
# Test cases
print(firstUniqChar("leetcode")) # Output: 0
print(firstUniqChar("loveleetcode")) # Output: 2
print(firstUniqChar("aabb")) # Output: -1
n
is the length of the string.Thus, the overall time complexity is O(n). The space complexity is also O(n) due to the dictionary used to store character counts.
This approach ensures we find the first unique character efficiently even for large input sizes up to the order of (10^5).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?