Problem 392

Abstract / Summary

Check if one string appears in the same order inside another string without changing the order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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();
    }
};
17 lines | 349 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (5+ million submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 s is longer than t, the early size comparison returns false without entering the loop, handling the impossibility of a subsequence.
  • An empty s triggers an immediate true, covering the mathematical definition that an empty sequence is a subsequence of any sequence, including an empty t.
  • The loop safely accesses s[S] only when S is within bounds because the early size check guarantees s is not longer than t, and the final comparison ensures S never exceeds s.size(). If S reaches s.size() before the loop ends, subsequent comparisons simply compare the out-of-range character with t[T], but the condition s[S] == t[T] will be false, leaving S unchanged. 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 (S and T) and no auxiliary containers, keeping the memory footprint minimal.
  • The linear scan processes each character of t exactly once, avoiding repeated passes or nested loops.
  • Early exit conditions (s.size() > t.size() and s.empty()) prevent unnecessary iteration when the answer is already known.
  • By incrementing S only 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.
written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.96 | σ = 1.07

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
50 links | 34 authors | 12 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

9 easy 2 medium 16 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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