LeetCode #392 Easy

Is Subsequence

Is Subsequence is LeetCode 392 (Easy). Given two strings s and t, return true if s is a subsequence of t.

  • A subsequence is what remains after deleting some characters of t, possibly none, without changing the order of the rest.
  • s has at most 100 letters and t at most 10,000, all lowercase.
  • Follow-up: if billions of different strings s are checked against the same t, how would you change the approach?
Constraints
  • 0 <= s.length <= 100
  • 0 <= t.length <= 10⁴
  • s and t consist only of lowercase English letters.
two-pointersstringgreedydynamic-programming
Open on LeetCode ↗
02

Intuition

Read t once from left to right and match each letter of s at the first place it can go. A pointer i marks the next letter of s still needed. Each letter of t gets one look: if it equals s[i], it is used and i moves on; otherwise it is skipped. If i reaches the end of s, every letter was found in order.

Taking the earliest match is never a mistake. If s[i] could also be matched further along t, matching it now leaves a longer tail of t for the rest of s, and anything that fits in a shorter tail also fits in a longer one.

How to spot this pattern

When one string must appear in order inside another, walk both with a pointer each: the longer one is read in full, the shorter one only advances on a match. The same two-pointer shape appears in merging sorted lists and in matching a pattern against a stream.

03

Approach

Try it first

Before reading on, find "ace" inside "abcde" by hand, keeping a finger on each string. When does each finger move? Then decide whether matching a letter as early as possible could ever stop a later letter from being found. Aim for one pass over t.

1

Put one pointer on each string

i marks the next letter of s still to be found, and j marks the next letter of t to read. Both start at 0 and neither moves backwards, so t is read only once.

2

Compare, then move

While both pointers are in range, compare s[i] with t[j]. On a match, move i forward, because that letter of s is now found. Move j forward every time, because a letter of t can be used at most once.

3

Answer from i

The loop stops when s is finished or t runs out. Return i == len(s): it is true exactly when every letter of s was matched, in order, to a letter of t.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isSubsequence(self, s: str, t: str) -> bool:
▶3 i = j = 0
▶4 while i < len(s) and j < len(t):
▶5 if s[i] == t[j]:
▶6 i += 1
▶7 j += 1
▶8 return i == len(s)
stabcahbgdcijboth pointers start at the first letter
i0next letter of s to find
j0next letter of t to read
i points at the next letter of s still to be found, and j at the next letter of t to read. Both only move forward, so t is read once.
stabcahbgdcija matches a → both move
s[i]a
t[j]a
i1
j1
a is the letter s needs next, and this is its first place in what is left of t. Taking the earliest place is safe: it leaves the longest tail of t for the letters after it.
stabcahbgdcijh ≠ b → skip h
s[i]b
t[j]h
i1stays
j2
h is not the b that s needs, so this letter of t is skipped for good. Only j moves; the letters of s already found stay found.
stabcahbgdcijb matches b → both move
s[i]b
t[j]b
i2
j3
b is the letter s needs next, and this is its first place in what is left of t. Taking the earliest place is safe: it leaves the longest tail of t for the letters after it.
stabcahbgdcijg ≠ c → skip g
s[i]c
t[j]g
i2stays
j4
g is not the c that s needs, so this letter of t is skipped for good. Only j moves; the letters of s already found stay found.
stabcahbgdcijd ≠ c → skip d
s[i]c
t[j]d
i2stays
j5
d is not the c that s needs, so this letter of t is skipped for good. Only j moves; the letters of s already found stay found.
stabcahbgdci = 3endc matches c → both move
s[i]c
t[j]c
i3
j6
c is the letter s needs next, and this is its first place in what is left of t. Taking the earliest place is safe: it leaves the longest tail of t for the letters after it. That was the last letter of s.
stabcahbgdci = 3endall 3 letters found → true
i3len(s) = 3
resulttrue
Every letter of s was found in order. s is a subsequence of t.
05

Common pitfalls

Requiring t to be used up too

✗ Wrong
return i == len(s) and j == len(t)
✓ Right
return i == len(s)

For s = "ace", t = "abcdefg" the loop stops as soon as e is found, with f and g unread, so this returns false. A subsequence may skip any part of t, including its end.

Looping over t without checking i

✗ Wrong
for c in t:
    if s[i] == c:
        i += 1
✓ Right
for c in t:
    if i < len(s) and s[i] == c:
        i += 1

Once all of s is matched, s[i] reads past its end. s = "a", t = "aa" raises an IndexError on the second a, and an empty s fails on the very first letter.

Testing for a substring instead

✗ Wrong
return s in t
✓ Right
while i < len(s) and j < len(t):
    ...

in looks for s as one unbroken block. "ace" is a subsequence of "abcde" because gaps are allowed, but "ace" in "abcde" is False.

06

Edge cases

s is empty

i already equals len(s), so the loop never runs and the answer is true: deleting every letter of t leaves the empty string.

s is longer than t

t runs out before i can reach the end of s, so the answer is false with no special check needed.

07

Complexity

Time
O(m)
Space
O(1)
m is the length of t. Every pass of the loop moves j forward by one, so there are at most m passes, and only the two pointers are stored.
08

Is Subsequence FAQ

How do you solve the follow-up with billions of strings s?

Do the work on t once. Store, for each letter, the sorted list of positions where it appears in t. For each query keep a position p, and for each letter of s binary search its list for the first position at or after p; if there is none, the answer is false, otherwise set p to that position plus 1. Each query then costs O(n log m) instead of O(m), where n is the length of s.

Can dynamic programming solve it?

Yes. s is a subsequence of t exactly when the longest common subsequence of the two has length len(s). That table costs O(n·m) time, so it is only worth knowing as the link to Longest Common Subsequence; the two-pointer scan does the same job in one pass.