
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).
1#include <stdio.h>
2#include <string.h>
3
4int firstUniqChar(char * s) {
5 int freq[26] = {0};
6 for (int i = 0; s[i] != '\0'; i++) {
7 freq[s[i] - 'a']++;
8 }
9 for (int i = 0; s[i] != '\0'; i++) {
10 if (freq[s[i] - 'a'] == 1) {
11 return i;
12 }
13 }
14 return -1;
15}
16
17int main() {
18 char s[] = "leetcode";
19 printf("%d\n", firstUniqChar(s));
20 return 0;
21}The function firstUniqChar tracks the frequency of each character in the string using an integer array. The first loop fills up the frequencies, and the second loop finds the first character with a frequency of one, returning its index. If no such character is present, it returns -1.
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)
1
This Python variant sets up a list of size 26 to manage character frequency tracking. A second iteration helps find the initial non-redundant character's index.