Is Subsequence - Problem

You are given two strings s and t. Your task is to determine whether s is a subsequence of t.

A subsequence is a sequence that can be derived from the original string by deleting some or no characters without changing the order of the remaining characters. Think of it as picking characters from left to right while maintaining their relative positions.

Examples:

  • "ace" is a subsequence of "abcde"
  • "aec" is NOT a subsequence of "abcde" ❌ (wrong order)
  • "axc" is NOT a subsequence of "abcde" ❌ ('x' doesn't exist)

Goal: Return true if s is a subsequence of t, otherwise return false.

Input & Output

example_1.py — Basic Match
$ Input: s = "ace", t = "abcde"
Output: true
💡 Note: We can find 'a' at position 0, 'c' at position 2, and 'e' at position 4, all in order.
example_2.py — Wrong Order
$ Input: s = "aec", t = "abcde"
Output: false
💡 Note: While all characters exist in t, 'e' comes after 'c', so we can't form the subsequence "aec".
example_3.py — Empty String
$ Input: s = "", t = "abcde"
Output: true
💡 Note: An empty string is always a subsequence of any string.

Visualization

Tap to expand
Subsequence Search VisualizationExample: s = "ace", t = "abcde"abcdeFound!SkipFound!SkipFound!Two Pointers Approach:Pointer i (for s): 0 → 1 → 2 (complete!)Pointer j (for t): 0 → 1 → 2 → 3 → 4Key Insight:We only need ONE pass through the target string!Time: O(n) | Space: O(1) where n = max(len(s), len(t))
Understanding the Visualization
1
Start Journey
Begin at the start of both your map (s) and the terrain (t)
2
Find Landmarks
When you find a landmark from your map, mark it as found and look for the next one
3
Keep Moving
Always move forward through the terrain, never backtrack
4
Success Check
You succeed if you find all landmarks from your map in order
Key Takeaway
🎯 Key Insight: The two pointers approach works because we only need to maintain the relative order of characters, not their exact positions.

Time & Space Complexity

Time Complexity
⏱️
O(n)

We traverse each string at most once, where n is the length of the longer string

n
2n
Linear Growth
Space Complexity
O(1)

Only using two pointer variables, no additional data structures needed

n
2n
Linear Space

Constraints

  • 0 ≤ s.length ≤ 100
  • 0 ≤ t.length ≤ 104
  • s and t consist only of lowercase English letters
Asked in
Google 45 Amazon 38 Meta 29 Microsoft 22 Apple 18
89.5K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen