Let's make this one less mysterious. For 392. Is Subsequence, the solution in this repository is mainly a greedy solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: greedy.
The notes already sitting in the source point us in the right direction:
- Greedy
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are isSubsequence, ss, cursors.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- 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
02//Runtime: 60 ms, faster than 87.38% of C++ online submissions for Is Subsequence.
03//Memory Usage: 17.1 MB, less than 66.67% of C++ online submissions for Is Subsequence.
04class Solution {
05public:
06 bool isSubsequence(string s, string t) {
07 int si = 0, ti = 0;
08 while(si < s.size() && ti < t.size()){
09 for(; ti < t.size() && s[si] != t[ti]; ti++){
10 // cout << s[si] << " " << t[ti] << endl;
11 }
12 /*
13 Greedy, unlike KMP, in which we need to fallback when encounted by a mismatch
14 In this case, the matched characters can always be kept, no need to drop them in a mismatch
15 In the example s = "abc", t = "ahbgdc",
16 when we know 'b' in s is different from 'h' in t,
17 we don't need to compare from 'a' in s again,
18 we just move forward the index on t.
19 */
20 if(s[si] == t[ti]){
21 //s[si] and t[ti] match, both seq go ahead
22 si++; //only if s[si] matches, we can go ahead in seq "s"
23 ti++;
24 }
25 }
26
27 //check if we look through s
28 return si == s.size();
29 }
30};
31
32//Greedy
33//https://leetcode.com/problems/is-subsequence/discuss/87272/3-lines-C
34class Solution {
35public:
36 bool isSubsequence(string s, string t) {
37 string::iterator si = s.begin();
38 for(char c : t){
39 si += (c == *si);
40 }
41 return si == s.end();
42 }
43};
44
45//Follow-up, compare vector<string> ss(S1,S2,...Sk) with string t
46//https://leetcode.com/problems/is-subsequence/discuss/87272/3-lines-C/92233
47//O(len(t) * K)
48class Solution {
49public:
50 bool isSubsequence(vector<string> ss, string t) {
51 int n = ss.size();
52 vector<int> cursors(n, 0);
53
54 for(char c : t){
55 //compare current char c in t with multiple strings in ss
56 for(int i = 0; i < n; i++){
57 cursors[i] += (ss[i][cursors[i]] == c);
58 }
59 }
60
61 vector<int> ans(n);
62 for(int i = 0; i < ss.size(); i++){
63 ans[i] = (cursors[i] == ss[i].size());
64 }
65
66 return ans;
67 }
68};
69
70//Follow-up, compare vector<string> ss(S1,S2,...Sk) with string t
71//https://leetcode.com/problems/is-subsequence/discuss/87272/3-lines-C/92233
72//skip redundant comparison
73//O(len(t) + sum(len(s[i])))
74class Solution {
75public:
76 bool isSubsequence(vector<string> ss, string t) {
77 int n = ss.size();
78 vector<int> cursors(n, 0);
79 vector<vector<int>> waitingList(26);
80
81 for(int i = 0; i < n; i++){
82 /*
83 for the char (ss[i][0]-'a'),
84 maintain the index of string in ss whose first char is that
85 */
86 waitingList[ss[i][0]-'a'].push_back(i);
87 }
88
89 for(char c : t){
90 vector<int> old = waitingList[c-'a'];
91 waitingList[c-'a'].clear();
92
93 //only visit the string in ss who are waiting for c
94 for(int i : old){
95 //ss[i] matches, move its cursor forward
96 cursors[i] += 1;
97 //update waitingList concurrently
98 waitingList[cursors[i]-'a'].push_back(i);
99 }
100 }
101
102 vector<int> ans(n);
103 for(int i = 0; i < ss.size(); i++){
104 ans[i] = (cursors[i] == ss[i].size());
105 }
106
107 return ans;
108 }
109};
Cost