Is Subsequence (LeetCode 392): Solution and Explanation

Easy
Two Pointers
String
Dynamic Programming

Decide whether string s can be obtained from string t by deleting some characters of t without reordering the rest. Return true if it can and false if it cannot.

Intuition

A brute force idea is to try every way of picking len(s) positions from t, which explodes combinatorially. Recursion with memoization on (i, j) brings that down to O(len(s) * len(t)), but there is a much simpler observation.

Suppose the first character of s appears several times in t. Matching it at its earliest occurrence is never worse than matching it later: any way of finishing the match from a later position also works from the earlier one, since more of t is still available. The same argument applies to every following character.

That turns the problem into a single greedy scan. Keep an index i into s for the next character you need. Walk j across t; whenever t[j] == s[i], that character is found, so advance i. Characters of t that do not match are just deleted.

When the scan ends, s is a subsequence exactly when i reached len(s). An empty s is trivially a subsequence of anything.

Approach: Greedy two-pointer scan

  1. Set i = 0, the index of the next character of s to find.
  2. Loop j over every index of t.
  3. If i < len(s) and s[i] == t[j], increment i.
  4. After the loop, return i == len(s).

Step-by-step example

s = "abc", t = "ahbgdc"
  1. j = 0: t[0] = 'a' equals s[0], so i becomes 1.
  2. j = 1: t[1] = 'h' is not 'b', skip.
  3. j = 2: t[2] = 'b' equals s[1], so i becomes 2.
  4. j = 3 and j = 4: 'g' and 'd' are not 'c', skip both.
  5. j = 5: t[5] = 'c' equals s[2], so i becomes 3.
  6. The scan ends with i = 3 = len(s), so the answer is true.

Code: Python, Java, C++

1class Solution:
2    def isSubsequence(self, s: str, t: str) -> bool:
3        i = 0
4        for j in range(len(t)):
5            if i < len(s) and s[i] == t[j]:
6                i += 1
7        return i == len(s)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

t is scanned once, where n = len(t); each step is a constant-time comparison.

Space

O(1)

Only the two indices are stored.

Other approaches

Next-position index with binary search (time O(len(s) log n) per query, space O(n))

Precompute, for each letter, the sorted list of its positions in t. For each character of s, binary search for the first position after the previous match. This is the answer to the follow-up with many s strings against one t: preprocessing is O(n) once and each query costs O(len(s) log n).

Longest common subsequence DP (time O(len(s) * n), space O(len(s) * n))

Compute the LCS of s and t and check whether it equals len(s). Correct but wasteful, since the greedy scan already answers the question.

Common mistakes

  • Reading s[i] after i has reached len(s). Guard the comparison with i < len(s) or break out once all of s is matched.
  • Returning false for an empty s. The empty string is a subsequence of every string, including the empty t.
  • Using t.find(c) from the start of t for every character, which ignores order and accepts inputs like s = "ba", t = "ab".
  • Advancing both pointers on a mismatch. Only j moves when the characters differ.

Frequently asked questions

Why is the greedy choice always safe?

Matching s[i] at the earliest possible t index leaves the largest suffix of t for the remaining characters. Any successful match that uses a later index can be rewritten to use the earlier one without breaking the rest.

How do you handle many s strings against the same t?

Build a map from each letter to the sorted positions where it occurs in t. For each query, keep the last matched position and binary search that letter's list for the next larger position. If none exists, the answer is false.

Can the loop stop early?

Yes. Once i == len(s) the answer is already true, so you can return immediately. It does not change the worst case, which is still one pass over t.