← Home

387. First Unique Character in a String

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
387

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 387. First Unique Character in a String, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are firstUniqChar, start, count.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N) since we go through the string of length N two times.
  • Space: O(N) since we have to keep a hash map with N elements.

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
03
04Examples:
05
06s = "leetcode"
07return 0.
08
09s = "loveleetcode",
10return 2.
11Note: You may assume the string contain only lowercase letters.
12**/
13
14//Runtime: 40 ms, faster than 86.06% of C++ online submissions for First Unique Character in a String.
15//Memory Usage: 12.8 MB, less than 99.44% of C++ online submissions for First Unique Character in a String.
16
17class Solution {
18public:
19    int firstUniqChar(string s) {
20        if(s.size() == 0) return -1;
21        
22        vector<int> start(26), count(26);
23        int ans = INT_MAX;
24        
25        for(int i = 0; i < s.size(); i++){
26            int cix = s[i] - 'a';
27            if(count[cix]==0){
28                start[cix] = i;
29                count[cix] = 1;
30            }else{
31                count[cix] += 1;
32            }
33        }
34        
35        for(int i = 0; i < 26; i++){
36            if(count[i] == 1){
37                ans = min(ans, start[i]);
38            }
39        }
40        
41        if(ans == INT_MAX) return -1;
42        
43        return ans;
44    }
45};
46
47/**
48Complexity Analysis
49
50Time complexity : O(N) since we go through the string of length N two times.
51Space complexity : O(N) since we have to keep a hash map with N elements.
52**/
53
54//Runtime: 40 ms, faster than 86.06% of C++ online submissions for First Unique Character in a String.
55//Memory Usage: 12.9 MB, less than 98.51% of C++ online submissions for First Unique Character in a String.
56class Solution {
57public:
58    int firstUniqChar(string s) {
59        int n = s.size();
60        
61        vector<int> count(26);
62        
63        for(char c : s){
64            count[c-'a'] += 1;
65        }
66        
67        for(int i = 0; i < n; i++){
68            if(count[s[i]-'a'] == 1) return i;
69        }
70        
71        return -1;
72    }
73};
74
75//Runtime: 200 ms, faster than 8.30% of C++ online submissions for First Unique Character in a String.
76//Memory Usage: 10.7 MB, less than 100.00% of C++ online submissions for First Unique Character in a String.
77class Solution {
78public:
79    int firstUniqChar(string s) {
80        vector<pair<char, int>> v;
81        for(int i = 0; i < s.size(); i++){
82            char c = s[i];
83            auto it = find_if(v.begin(), v.end(), 
84                [&c](const pair<char, int>& p){return p.first == c;});
85            if(it == v.end()){
86                //first meet
87                v.push_back(make_pair(c, i));
88            }else{
89                it->second = -1;
90            }
91        }
92        
93        int ans = -1;
94        
95        for(pair<char,int>& p : v){
96            if(p.second != -1){
97                ans = p.second;
98                break;
99            }
100        }
101        
102        return ans;
103    }
104};

Cost

Complexity

Time
O(N) since we go through the string of length N two times.
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(N) since we have to keep a hash map with N elements.
Auxiliary state plus the answer structure where the problem requires one.