LC 387. First Unique Character in a String

Sarthak Sehgal · May 5, 2020

The solution below is straightforward. We iterate the string once and count the frequency of each character. Note that the string only contains lowercase letters so instead of using a hashmap, we can simply use an array of size 26 to keep track of frequency. We then iterate the array again and return the index of the first character whose frequency is 1. If no such character is found, we return -1.

class Solution {
public:
    int firstUniqChar(string s) {
        vector<int> cnt(26, 0);
        for (char c : s) cnt[c-'a']++;
        for (int i=0; i<s.length(); i++)
            if (cnt[s[i]-'a']==1)
                return i;

        return -1;
    }
};

Time complexity: O(n)
Space complexity: O(1)

Twitter, Facebook