Is Subsequence
LeetCode 392 • Easy • Two Pointers
Return true if s is a subsequence of t. Two pointers: match s[i] in t, advance i on match, always advance j.
TimeO(n)single pass over t
SpaceO(1)two pointers
i: —
j: —
Result: —
Ready
Press Play. Two pointers: i on s, j on t. If s[i]==t[j], advance i; always advance j. Return i==len(s).
TimeO(n)single pass
SpaceO(n)call stack
Recursive: helper(i, j) — base: if i==len(s) return True; if j==len(t) return False; if s[i]==t[j] return helper(i+1,j+1); return helper(i,j+1).
3
Practice until you don't need to look. Use the guide comments below as scaffolding. The green highlights are the nuances to burn into memory.
# ─── IS SUBSEQUENCE (LeetCode 392) ───
# Pattern: Two pointers — match s[i] in t; i++ on match, j++ always
# Time: O(n) Space: O(1)
#
# 1. Define: isSubsequence(s, t)
#
# 2. Base: if not s: return True
#
# 3. Init pointers: i, j = 0, 0
#
# 4. Loop: while i < len(s) and j < len(t):
#
# 5. Match: if s[i] == t[j]: i += 1
# 6. Always advance j: j += 1
#
# 7. Return: return i == len(s)
#
# Vars: i, j
▼ your implementation ▼
Verify your solution: