Is Subsequence - Problem

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. For example, "ace" is a subsequence of "abcde" while "aec" is not.

Input & Output

Example 1 — Basic Subsequence
$ Input: s = "abc", t = "aabbcc"
Output: true
💡 Note: We can find 'a', then 'b', then 'c' in order within "aabbcc": a(a)b(b)c(c)
Example 2 — Not a Subsequence
$ Input: s = "axc", t = "ahbgdc"
Output: false
💡 Note: We find 'a', then find 'h', 'b', 'g', 'd' but no 'x' appears before 'c'
Example 3 — Empty Subsequence
$ Input: s = "", t = "hello"
Output: true
💡 Note: Empty string is always a subsequence of any string

Constraints

  • 0 ≤ s.length ≤ 100
  • 0 ≤ t.length ≤ 104
  • s and t consist only of lowercase English letters

Visualization

Tap to expand
Is Subsequence - Two Pointer Approach INPUT String s (to find): a b c 0 1 2 String t (source): a a b b c c 0 1 2 3 4 5 Matched Skipped Input Values: s = "abc" t = "aabbcc" ALGORITHM STEPS 1 Initialize Pointers i=0 for s, j=0 for t 2 Compare Characters If s[i] == t[j], move i 3 Always Move j Advance through t 4 Check Completion Return i == len(s) Execution Trace: j t[j] s[i] Match? 0 a a OK i=1 1 a b skip 2 b b OK i=2 3 b c skip 4 c c OK i=3 FINAL RESULT Subsequence Found! Characters matched in order: a a b b c c a b c = "abc" (complete match) Output: true i reached len(s) = 3 "abc" IS a subsequence Key Insight: The two-pointer technique efficiently checks subsequence by scanning t once (O(n) time, O(1) space). We only move the s-pointer when characters match, ensuring we preserve the relative order. If the s-pointer reaches the end, all characters were found in order ---> subsequence exists! TutorialsPoint - Is Subsequence | Two Pointer Approach (Optimal Solution)
Asked in
Amazon 8 Google 5 Microsoft 4 Facebook 3
285.0K Views
Medium Frequency
~15 min Avg. Time
4.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