392. Is Subsequence
At a Glance
- Topic: two-pointers
- Pattern: Two Pointers
- Difficulty: Easy
- Companies: Amazon, Google, Meta, Bloomberg, Microsoft
- Frequency: High
- LeetCode: 392
Problem (one-liner)
Given strings source and stream, return whether source can be obtained by deleting some (possibly zero) characters from stream without reordering the rest.
Recognition Cues
- "Subsequence" vs substring
- Scan longer string once while matching shorter
- Greedy: match
sourceleft-to-right instream
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — DP LCS-style —
O(m*n)time — overkill. - Better — two pointers —
O(m+n)time /O(1)space — one pass. - Optimal — same two-pointer greedy — proven for subsequence check.
Optimal Solution
Go
func isSubsequence(source string, stream string) bool {
if len(source) == 0 {
return true
}
match := 0
for index := 0; index < len(stream) && match < len(source); index++ {
if stream[index] == source[match] {
match++
}
}
return match == len(source)
}JavaScript
function isSubsequence(source, stream) {
if (source.length === 0) {
return true;
}
let matched = 0;
for (let index = 0; index < stream.length && matched < source.length; index++) {
if (stream[index] === source[matched]) {
matched++;
}
}
return matched === source.length;
}Walkthrough
Input: source = "abc", stream = "ahbgdc"
| index | stream[index] | matched | note |
|---|---|---|---|
| 0 | a | 1 | match 'a' |
| 1 | h | 1 | skip |
| … | b | 2 | … |
Invariant: matched counts longest prefix of source found as a subsequence so far.
Edge Cases
- Empty
source(true) sourcelonger thanstream(false)- Equal strings
Pitfalls
- Restarting
matchedon mismatch (never restart — subsequence is greedy) - Confusing with substring (contiguous)
Similar Problems
- 125. Valid Palindrome — two-ended string scan.
- 680. Valid Palindrome II — at most one edit to palindrome.
- 283. Move Zeroes — forward scan with conditional advance (pointer discipline).
Variants
- Many queries on same
stream— preprocess indices per letter + binary search each step. - Longest common subsequence — DP when not greedy.
Mind-Map Tags
#two-pointers #subsequence #greedy-match #string-scan
Last updated on
Spotted something unclear or wrong on this page?