392. Is Subsequence¶
Edited by Charles
Easy · Python · Array
Problem
Read the original problem on LeetCode.
The official page contains the problem statement, examples, and constraints.
Explanation, examples & other approaches
Core idea
Use two pointers:
ipoints to the current character insjpoints to the current character int
Original study notes follow, including intermediate snippets and earlier attempts.
Problem¶
Given two strings s and t, return True if s is a subsequence of t, otherwise return False.
A subsequence is a string that can be derived from another string by deleting some characters without changing the relative order of the remaining characters.
Example¶
Approach: Two Pointers¶
Use two pointers:
ipoints to the current character insjpoints to the current character int
The pointer j always moves forward because we are searching through t.
The pointer i only moves forward when we successfully find s[i] in t.
Case 1: Characters Match¶
If:
we have found the current character of s, so move i forward:
Case 2: Characters Do Not Match¶
If:
we still need to find s[i], so i stays unchanged.
We only move j forward to continue searching in t.
Therefore, j moves forward in every iteration:
Example Walkthrough¶
Start:
Step 1¶
Match:
Step 2¶
Keep i at b, move j:
Step 3¶
Match:
Step 4¶
Move j.
Step 5¶
Move j.
Step 6¶
Now all characters in s have been matched.
Therefore:
and the answer is True.
Why return i == len(s)?¶
i represents how many characters of s have been successfully matched.
If:
then every character in s has been found in t in the correct order.
Therefore, s is a subsequence of t.
Complexity¶
Let n = len(t).
- Time:
O(n) - Space:
O(1)
Each character in t is visited at most once.
Key Idea¶
In code:
This preserves the relative order of characters in s, which is exactly what the definition of a subsequence requires.
Study record
| Field | Value |
|---|---|
| Attempts | 1 |
| Mastery | ❚ |
| The Latest Attempt | October 3, 2026 |
Python solution¶
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i, j = 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s)