40ms C++ solution

  • 0
        int firstUniqChar(string s) {
            vector<pair<int, int>> characters (26, std::make_pair(0, -1));
            for(int i=0; i<s.length(); i++){
                if(characters[s[i]-'a'].second==-1) characters[s[i]-'a'].second=i;
            int smallest = INT_MAX;
            for(auto character:characters){
                if(character.first==1 && character.second<smallest) smallest=character.second;
            return smallest==INT_MAX?-1:smallest;

    Index to store which character, pair to store firstly occurrence index and total occurrences.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.