My Simple C++ solution (O(n) time, O(1) space)

  • 0
    class Solution {
        int firstUniqChar(string s) {
            vector<int> table(26, 0);
            for(int i = 0; i < s.size(); i++){
            for(int i = 0; i < s.size(); i++){
                if(table['a'] == 1) return i;
            return -1;

    Don't forget that in the constraint it states that we are limited to lowercase letters only. This means we only require an array of length 26.

    In this solution, I iterated over the string and counted the number of letters. Then I iterated again, and for each letter in the string checked if its count was one. Obviously you'll hit the first unique letter first, and if not return -1;

Log in to reply

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