THN Interview Prep

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 source left-to-right in stream

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"

indexstream[index]matchednote
0a1match 'a'
1h1skip
b2

Invariant: matched counts longest prefix of source found as a subsequence so far.

Edge Cases

  • Empty source (true)
  • source longer than stream (false)
  • Equal strings

Pitfalls

  • Restarting matched on mismatch (never restart — subsequence is greedy)
  • Confusing with substring (contiguous)

Similar Problems

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?

On this page