15% off all plans & roadmaps Use code

See plans

Is Subsequence

Updated

TL;DR: Decide whether `s` is a subsequence of `t` by matching the letters of `s` greedily, left to right, against `t`. One forward pass over `t` settles it in O(m) time and O(1) extra space.

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 formed from the original by deleting some (possibly none) of its characters without changing the relative order of the rest. For example, ace is a subsequence of abcde, while aec is not.

Example 1

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2

Input: s = "axc", t = "ahbgdc"
Output: false

Constraints

  • 0 <= s.length <= 100
  • 0 <= t.length <= 10^4
  • s and t consist only of lowercase English letters.

Constraints that matter

  • t.length up to 10^4 rules out any search over subsets of t, since a subset search has 2^m candidates.
  • s.length up to 100 keeps an n by m table near 10^6 cells. That is affordable, but it wastes memory a single scan does not need.
  • A single linear pass over t, which is O(m), fits the limit with room to spare.
  • Only lowercase letters appear, so a list of positions per letter is possible. It only pays off when many strings s share the same t.

View on LeetCode

Hints

Hint 1

You must find the letters of s inside t in the same order, but you may skip any letters of t.

Hint 2

Start with the most literal approach.

Solution

Intuition

You must find the letters of s inside t in the same order, but you may skip any letters of t. Each match uses up one letter of s and a stretch of t. The real question is which match to take when several are available.

Take the earliest match every time. This greedy choice is safe. If the next letter of s can match t[p] or a later t[q], picking t[p] leaves a longer tail of t for the rest of s. A longer tail never makes a later match harder.

This is the two pointers pattern. One index walks through all of t, and a second index walks through s and moves only when a match happens. No cycle forms, so the fast and slow label does not apply. The scan is one forward pass with two indices.

Look for the signal in the wording: one string must appear inside another in order, with gaps allowed. Whenever the problem asks for an order-preserving match of that kind, try a forward scan with one index per string first.

Watch the pattern animation

Worked example

Input: s = "aaaaa", t = "aaaaaaaaaa"
Output: true
Explanation: The string t holds ten a's and s needs only five. Any five of those a's, taken in order, spell s, so the answer is true.

Approach 1: Brute force: suffix table over every pair

Start with the most literal approach. Ask a smaller question for every pair of positions. Let dp[i][j] say whether the suffix s[i:] is a subsequence of t[j:], and fill the whole table from the bottom right.

Each cell either skips t[j] or, when the letters match, uses t[j] and moves both indices forward. Filling every cell answers every pair, and dp[0][0] is the answer. The work grows with the product of the two lengths.

Steps

  1. Let n be the length of s and m the length of t.
  2. Create an (n + 1) by (m + 1) table of booleans.
  3. Set the whole last row, row n, to true. An empty suffix fits anywhere.
  4. For i from n - 1 down to 0, and j from m - 1 down to 0, set dp[i][j] to dp[i][j + 1] or (s[i] equals t[j] and dp[i + 1][j + 1]).
  5. Return dp[0][0].

Dry run

Here s is five a's and t is ten a's, so the table has 6 rows (i from 0 to 5) and 11 columns (j from 0 to 10).

Row 5 is all true, because an empty suffix fits anywhere. Row 4 holds one a, which fits in any suffix that contains an a, so it is true for columns 0 to 9 and false at column 10.

Moving up one row needs one more a, so each row's true run ends one column earlier. Row 0 is true for columns 0 to 5. Since dp[0][0] is true, the function returns true.

Complexity

TimeO(n * m)
SpaceO(n * m)

Let n be the length of s and m the length of t. The table has (n + 1) times (m + 1) cells, and each cell does a fixed amount of work, so time is O(n * m). The table is stored in full, so space is also O(n * m).

PythonTested in our runner

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        n, m = len(s), len(t)
        # dp[i][j] is True when s[i:] is a subsequence of t[j:]
        dp = [[False] * (m + 1) for _ in range(n + 1)]
        for j in range(m + 1):
            dp[n][j] = True
        for i in range(n - 1, -1, -1):
            for j in range(m - 1, -1, -1):
                dp[i][j] = dp[i][j + 1] or (s[i] == t[j] and dp[i + 1][j + 1])
        return dp[0][0]

The Fast & Slow (Cycle Detection) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Fast & Slow (Cycle Detection)

Part of Two Pointers

Approach 2: Greedy two pointersOptimalFast & Slow (Cycle Detection)

What is slow in the table is that it stores an answer for every pair (i, j). Only one path through those pairs matters, and most cells are never needed. Each row also rebuilds work from the row below it.

The insight that fixes it: match greedily from the left. Walk t once, and each time the current letter of s appears, advance past it. That visits exactly one path, and only one index into s has to be remembered.

Steps

  1. Set i to 0. It points at the next letter of s you still need.
  2. Walk j through t from index 0 to the end, one letter at a time.
  3. When t[j] equals s[i], increment i. Otherwise leave i alone.
  4. Stop early if i reaches len(s), because the answer is already known.
  5. Return whether i equals len(s).

Dry run

Start with i = 0 and walk through t. Every letter of t is an a, and s needs a at every position, so each step matches.

Stepjt[j]i befores[i]Matchi after
10a0ayes1
21a1ayes2
32a2ayes3
43a3ayes4
54a4ayes5

After step 5, i equals len(s), which is 5. The remaining letters of t change nothing, so the function returns true. An early break would stop at the same result.

Complexity

TimeO(m)
SpaceO(1)

Let m be the length of t. The loop runs once per letter of t, and each pass does one comparison and at most one increment. i increments at most min(n, m) times, so the total work is at most 2m, which is O(m). Only i and the loop variable exist, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        i = 0  # index of the next character of s to match
        for ch in t:
            if i < len(s) and s[i] == ch:
                i += 1
        return i == len(s)

Common mistakes

  • Placing i += 1 outside the if, so every letter of t advances i. With s = ab and t = xb, the x wrongly consumes a letter of s and the function returns true. Increment i only inside the match branch.
  • Reading s[i] before checking i < len(s). Once i reaches the length of s, that read is out of range. Put the length check first, joined with and or &&.
  • Using s in t, t.contains(s) or a similar substring test. Substring checks need contiguous letters, so ace in abcde returns false. The gaps are the whole point of the problem.
  • Comparing letter counts instead of order. Equal counts say ca matches abc, which is wrong because the c comes after the a in t. The forward scan keeps the order.
  • Returning false for an empty s with a guard such as if not s: return False. The empty string is a subsequence of every string, including the empty string.
  • In the table version, leaving row n as false. Then dp[n][j] says the empty suffix does not fit, and every answer becomes false. Set the whole last row to true before the loops.

Edge cases

  • s is empty and t is anything, including empty. Expected: true, since the empty string is always a subsequence.
  • t is empty and s is not. Expected: false. The scan never matches, so i stays 0 and differs from len(s).
  • s is longer than t, for example 11 a's against 10 a's. Expected: false, because i can never reach 11.
  • s equals t, such as abc and abc. Expected: true, with every letter matching in order.
  • Order is reversed, such as s = ca and t = abc. Expected: false, because the c in t comes after the a.
  • The last letter of s matches the last letter of t, with gaps before it, such as s = ac and t = abc. Expected: true.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Is Subsequence, with how to answer them.

Unlock the follow-ups

Is Subsequence FAQ

What is the time complexity of Is Subsequence?

The two-pointer solution runs in O(m) time, where m is the length of t, and uses O(1) extra space. The table version takes O(n * m) time and space, where n is the length of s. Both bounds come from counting the passes over the input.

Why use two pointers for Is Subsequence?

Both strings are read in the same left-to-right order, so one index per string fits. Each index only moves forward, so the total movement is bounded by the two lengths. Taking the earliest match is safe, so one pass decides the answer.

Can Is Subsequence be solved in O(1) extra space?

Yes. The forward scan keeps a single index into s and nothing else. It never stores any part of t, so the extra space does not grow with the input.

Is a subsequence the same as a substring?

No. A substring must be contiguous, so ace is a subsequence of abcde but not a substring of it. A subsequence may skip characters, as long as the remaining characters keep their order.

Why does the greedy scan never need to backtrack?

Matching a letter at its earliest position leaves the largest possible tail of t. A later match only leaves less room for the rest of s. So if any valid matching exists, the earliest-match version finds one.

Why does the empty string count as a subsequence?

Deleting every character is allowed, so the empty string is a subsequence of any string. The scan returns true because i stays at 0, which equals the length of the empty s.

Asked at

See which companies ask this — Pro

Practise it