
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 <iostream>
2#include <string>
3#include <unordered_map>
4using namespace std;
5
6int firstUniqChar(string s) {
7 unordered_map<char, int> freq;
8 for (char c : s) {
9 freq[c]++;
10 }
11 for (int i = 0; i < s.size(); ++i) {
12 if (freq[s[i]] == 1) {
13 return i;
14 }
15 }
16 return -1;
17}
18
19int main() {
20 string s = "leetcode";
21 cout << firstUniqChar(s) << endl;
22 return 0;
23}In this C++ solution, we use an unordered_map to store character frequencies. We then iterate over the string to fetch the first unique character, returning its index. If no unique character exists, we return -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)
This JavaScript code tracks the frequency of characters using a fixed-size array, enabling identification of the initial unique character and its index through a second iteration.