Is Subsequence

Easy

Topics
StringTwo PointersDynamic Programming

Given two strings s and t, return true if s is a subsequence of t (formed by deleting some characters of t without changing the order of the rest).

Example 1

sabc
tahbgdc
The shaded characters of t spell s in order, though not contiguously — so the answer is true.
Rows are the two strings; shaded cells in t are the greedy match for s.
Input:  s = "abc", t = "ahbgdc"
Output: true

Example 2

saxc
tahbgdc
Scanning forward through t runs out of string before matching all of s, so the answer is false.
Input:  s = "axc", t = "ahbgdc"
Output: false

Constraints

  • 0 <= s.length <= 100
  • 0 <= t.length <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Greedily match the characters of s against t in order. Advance through t; whenever it matches the current needed character of s, move to the next needed character. If we consume all of s, it is a subsequence.

Approach

  1. Pointer i into s.
  2. Walk t; when t[j] == s[i], advance i.
  3. If i reaches the end of s, return True.

Walkthrough

s = "abc", t = "ahbgdc"
a matches a, b matches b, c matches c -> consumed all of s -> true

Complexity

  • Time — O(|t|): one pass over t.
  • Space — O(1): two indices.

Common Pitfalls

  • An empty s is a subsequence of anything — the pointer starts already "consumed".

Full Solution — all languages

class Solution:
    def isSubsequence(self, s, t):
        it = iter(t)
        return all(c in it for c in s)
Asked at Pinterest Tesla
SensAI
Beta
Tap the mic to stop voice mode