Is Subsequence
LeetCode 392 · Easy · solution, intuition & step-by-step walkthrough
Greedy two-pointer match.
This is how I solved Is Subsequence (LeetCode 392), an easy problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Scan t once; whenever its character matches the next needed character of s, advance in s. If you consume all of s, it's a subsequence.
Approach
- 1
i over s, j over t.
- 2
Match → advance both; otherwise advance only j.
- 3
Return i == len(s).
How I solved it
Two pointersPythonO(n) time · O(1) space
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i=0
j=0
while i<len(s) and j<len(t):
if s[i]==t[j]:
i+=1
j+=1
else:
j+=1
return i==len(s)Is Subsequence — FAQ
What is the intuition behind Is Subsequence?
Scan t once; whenever its character matches the next needed character of s, advance in s. If you consume all of s, it's a subsequence.
How do you solve Is Subsequence (LeetCode 392)?
1. i over s, j over t. 2. Match → advance both; otherwise advance only j. 3. Return i == len(s).
What is the time and space complexity of Is Subsequence?
Time: O(|t|). Space: O(1). (Accepted approach: Two pointers.)
What are common mistakes in Is Subsequence?
An empty s is always a subsequence.