C++ 0392.cpp
class Solution {
public:
bool isSubsequence(string s, string t) {
if (s.size() > t.size())
return false;
if (s.empty())
return true;
int S = 0;
for (int T = 0; T < t.size(); T++)
if (s[S] == t[T])
S++;
return S == s.size();
}
};
Difficulty
and has an acceptance rate of about 49% (5+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- String
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method isSubsequence that determines whether the string s appears as a subsequence within the string t. A subsequence preserves the relative order of characters but does not require them to be contiguous. The implementation follows a straightforward linear scan approach, using two integer indices to traverse the strings.
Key Steps
Input Validation
Before any processing, the method checks two simple conditions that can immediately decide the outcome.
if (s.size() > t.size())
return false;
if (s.empty())
return true;
The first condition eliminates cases where s cannot possibly fit inside t because it is longer. The second condition treats an empty s as a trivially satisfied subsequence, returning true without further work.
Iteration Through Target String
The core logic walks through t once, advancing a pointer in s whenever a matching character is found.
int S = 0;
for (int T = 0; T < t.size(); T++)
if (s[S] == t[T])
S++;
Here S tracks the current position in s. The loop variable T iterates over each character of t. When t[T] matches the current character s[S], the index S is incremented, moving to the next character to be matched. The loop continues until the end of t is reached.
Result Determination
After the scan, the method verifies whether all characters of s have been matched.
return S == s.size();
If S has advanced to the length of s, every character was found in order, and the function returns true. Otherwise, it returns false.
Edge Cases Handled
The implementation explicitly addresses several boundary conditions:
- When
sis longer thant, the early size comparison returnsfalsewithout entering the loop, handling the impossibility of a subsequence. - An empty
striggers an immediatetrue, covering the mathematical definition that an empty sequence is a subsequence of any sequence, including an emptyt. - The loop safely accesses
s[S]only whenSis within bounds because the early size check guaranteessis not longer thant, and the final comparison ensuresSnever exceedss.size(). IfSreachess.size()before the loop ends, subsequent comparisons simply compare the out-of-range character witht[T], but the conditions[S] == t[T]will be false, leavingSunchanged. The final equality check correctly reflects that all required characters have already been matched.
Performance Optimizations
The algorithm is optimized for speed and memory usage in several ways:
- It uses only two integer variables (
SandT) and no auxiliary containers, keeping the memory footprint minimal. - The linear scan processes each character of
texactly once, avoiding repeated passes or nested loops. - Early exit conditions (
s.size() > t.size()ands.empty()) prevent unnecessary iteration when the answer is already known. - By incrementing
Sonly on matches, the method avoids extra work such as searching ahead or backtracking, ensuring that each character comparison contributes directly to progress toward the final result.
ELI5 - Simplified Explanation
Imagine there are two lines of people waiting for a snack. The first line is a small group of friends who want to get their treats in a specific order, and the second line is a long queue of everyone else. To see if the small group is hidden inside the long queue, we start by checking the first friend in the small group and looking through the long line one person at a time. Every time we find a match in the long line, we know that friend is taken care of, so we move on to find the next friend in the small group. We keep going until we search through everyone in the long line. If we successfully found all of the friends in the small group, then the group is truly hidden inside the queue.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | C# | C | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 792: Number of Matching Subsequences
- problem 2486: Append Characters to String to Make Subsequence
- problem 2825: Make String a Subsequence Using Cyclic Increments
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality