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:
s = "leetcode"
Output: 0
Explanation: The character 'l' at index 0 is the first character that does not occur at any other index.
Example 2:
s = "loveleetcode"
Output: 2
Example 3:
s = "aabb"
Output: -1
Constraints:
1 <= s.length <= 10^5
s
consists of only lowercase English letters.A brute force approach would involve iterating through the string for each character to check if it repeats. For each character, we would iterate through the rest of the string to see if the same character appears again. If it doesn't, we've found our first non-repeating character.
Code (Python):
def first_unique_char_brute_force(s):
for i in range(len(s)):
is_unique = True
for j in range(len(s)):
if i != j and s[i] == s[j]:
is_unique = False
break
if is_unique:
return i
return -1
Time Complexity: O(n^2), where n is the length of the string. Space Complexity: O(1), as we use only a constant amount of extra space.
We can optimize this by using a hash map (dictionary in Python) to store the frequency of each character. Then, we can iterate through the string once more to find the first character with a frequency of 1.
Code (Python):
def first_unique_char(s):
char_counts = {}
# Count character frequencies
for char in s:
char_counts[char] = char_counts.get(char, 0) + 1
# Find the first unique character
for i, char in enumerate(s):
if char_counts[char] == 1:
return i
return -1
Explanation:
s
and counts the occurrences of each character, storing them in the char_counts
dictionary.s
again, this time checking the frequency of each character in the char_counts
dictionary. If a character has a frequency of 1, it means it's unique, and we return its index.Time Complexity: O(n), where n is the length of the string. This is because we iterate through the string twice.
Space Complexity: O(1). The size of the hash map will be, at most, the number of unique characters in the string. Since the string consists of lowercase English letters, the hash map can contain at most 26 key-value pairs, making the space complexity constant.