
Sponsored
Sponsored
This approach employs a hash map to store the frequency of each character in the string. Then, by iterating through the string again, we can find the first character with a frequency of 1 and return its index. If no such character is found, we return -1.
Time Complexity: O(n), where n is the length of the string, as we traverse through the string twice.
Space Complexity: O(1), because the array size is constant (26 letters of the English alphabet).
1def firstUniqChar(s: str) -> int:
2 freq = {}
3 for c in s:
4 freq[c] = freq.get(c, 0) + 1
5 for i, c in enumerate(s):
6 if freq[c] == 1:
7 return i
8 return -1
9
10print(firstUniqChar("leetcode"))This Python solution uses a dictionary to store the frequency of each character in the string. It then looks for the first character with a frequency of 1 and returns its index.
This approach involves iterating through the input string two times without using any auxiliary space like a hash map or dictionary. In the first iteration, we use an array to count the occurrences of each character. In the second iteration, we check for the first character that appears only once by referring to the count array. We conclude by returning its index or -1 if no such character is found.
Time Complexity: O(n)
Space Complexity: O(1)
The C solution involves a simple integer array of size 26, corresponding to each lowercase letter, and populating it with frequencies of the characters present. By going over the string a second time, the index of the first non-repeating character is identified.