I like to read this solution as a small machine: keep the useful information, throw away the noise. For 316. Remove Duplicate Letters, the solution in this repository is mainly a stack solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. 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: stack, greedy.
The notes already sitting in the source point us in the right direction:
- Greedy + recursion
- https://leetcode.com/problems/remove-duplicate-letters/discuss/76768/A-short-O(n)-recursive-greedy-solution
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are removeDuplicateLetters, counter, visited.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
- Substring checks are convenient but not free, so they are part of the real complexity story.
- 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:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- 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) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Greedy + recursion
02//https://leetcode.com/problems/remove-duplicate-letters/discuss/76768/A-short-O(n)-recursive-greedy-solution
03//Runtime: 16 ms, faster than 17.06% of C++ online submissions for Remove Duplicate Letters.
04//Memory Usage: 8.8 MB, less than 5.05% of C++ online submissions for Remove Duplicate Letters.
05class Solution {
06public:
07 string removeDuplicateLetters(string s) {
08 int n = s.size();
09
10 if(n == 0)
11 return "";
12
13 vector<int> counter(26, 0);
14
15 for(char& c : s){
16 ++counter[c-'a'];
17 }
18
19 int start = 0;
20 for(int i = 0; i < n; ++i){
21 if(s[i] < s[start]){
22 start = i;
23 }
24 --counter[s[i]-'a'];
25 //there are counter[s[i]-'a'] s[i] in s[i+1...]
26 if(counter[s[i]-'a'] == 0){
27 //skip those index s.t. s[i] is missing
28 break;
29 }
30 }
31
32 string nexts = s.substr(start+1);
33 auto it = remove(nexts.begin(), nexts.end(), s[start]);
34 nexts = std::string(nexts.begin(), it);
35 // cout << "remove " << s[start] << ", next: " << nexts << endl;
36 return s[start]+removeDuplicateLetters(nexts);
37 }
38};
39
40//Greedy + stack
41//https://leetcode.com/problems/remove-duplicate-letters/discuss/76769/Java-solution-using-Stack-with-comments
42//Runtime: 4 ms, faster than 95.18% of C++ online submissions for Remove Duplicate Letters.
43//Memory Usage: 6.7 MB, less than 59.72% of C++ online submissions for Remove Duplicate Letters.
44class Solution {
45public:
46 string removeDuplicateLetters(string s) {
47 vector<int> counter(26, 0);
48
49 //the stack stores the char used to construct the answer
50 stack<char> stk;
51 //a look up table for the stack, used to check whether a char is added into the stack
52 vector<bool> visited(26, false);
53
54 int n = s.size();
55
56 for(int i = 0; i < n; ++i){
57 ++counter[s[i]-'a'];
58 }
59
60 for(char& c : s){
61 --counter[c-'a'];
62
63 //skip duplicate char
64 if(visited[c-'a'])
65 continue;
66
67 /*
68 current char is smaller,
69 after ensuring that there are more "stk.top()" after current char,
70 we can safely remove it from stack
71 (the char "stk.top()" will later be added again)
72 */
73
74 /*
75 for large char, after it is pushed into stack,
76 it will be popped again,
77 so it will be put as later as possible
78 */
79 while(!stk.empty() && c < stk.top() && counter[stk.top()-'a'] > 0){
80 char topc = stk.top();
81 stk.pop();
82 visited[topc-'a'] = false;
83 }
84
85 /*
86 for small char, after it is pushed into stack,
87 it won't be popped again,
88 so it can be put at former place in the final string
89 */
90 stk.push(c);
91 visited[c-'a'] = true;
92 }
93
94 string ans;
95
96 while(!stk.empty()){
97 ans = stk.top() + ans;
98 stk.pop();
99 }
100
101 return ans;
102 }
103};
Cost