
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#include <vector>
#include <string>
using namespace std;
int firstUniqChar(string s) {
vector<int> count(26, 0);
for (char c : s) {
count[c - 'a']++;
}
for (int i = 0; i < s.length(); ++i) {
if (count[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
int main() {
cout << firstUniqChar("loveleetcode") << endl;
return 0;
}For this C++ solution, a vector is used to tally character frequencies for each letter based on their indices. A second loop reveals the index where the first unique character occurs.