You are given two strings, s and t. Decide whether s is a subsequence of t: whether you can get s by crossing out some letters of t (possibly none) and reading what is left from left to right.
The letters you keep must stay in their original order, but they do not have to sit next to each other. Return true or false.
Example 1
Input: s = "dog", t = "doorbag" Output: true Why: keep d, o and g; cross out o, r, b, a
2 more examples and the constraints
Example 2
Input: s = "god", t = "doorbag" Output: false Why: the only g is the last letter of t
Example 3
Input: s = "", t = "xyz" Output: true Why: cross out every letter to get the empty string
Constraints
- 0 ≤ length of s ≤ 100
- 0 ≤ length of t ≤ 10,000
- Both strings use only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Prefix table (DP)O(n·m)
- Two pointersO(n + m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Steps for s of 100 letters and t of 10,000 | Verdict |
|---|---|---|---|
| Prefix table (DP) | O(n·m) | Passes; far more work | |
| Two pointers | O(n + m) | Best; one scan |
n = length of s, m = length of t.
Edge cases to test
- Empty s. The empty string is a subsequence of anything, even an empty t: return true.
- Empty t. Any non-empty s fails: "a" in "" is false.
- Repeated letters. "aab" fits in "abab" by using both a's, but "aaa" does not: each letter of t can be used once.
- s longer than t. It can never fit; the scan ends with i short of the end.
Common mistakes
- Checking only that every letter of s appears in t, ignoring their order.
- Reading
s[i]after i has reached the end of s, which overflows the string. - Matching one letter of t to two letters of s, for example forgetting to advance j.
How to talk through it
- 1Clarify. Can s be empty? Must the letters be next to each other, or only in order?
- 2Say the greedy rule. Match each letter of s at its first chance in t; an earlier match leaves more of t for the rest.
- 3Code the scan. One index into s, one loop over t, and a final check that i reached the end.
- 4Answer the follow-up. For many s against one t, keep position lists per letter and binary-search them.
- 5Test out loud. Run empty s, empty t, the wrong-order case and a repeated letter before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?