SDE & MLE Prep

392. Is Subsequence

Problem

Decide whether s is a subsequence of t: can s be obtained by deleting zero or more characters of t without reordering the rest?

Example: s = "abc", t = "ahbgdc" → true; s = "axc" → false

Constraints: follow-up: many different s queried against the same t.

Greedy match: advance in s whenever t[j] equals s[i]. Success if all of s is consumed. Follow-up (many s queries): index positions of each char in t, then binary-search the next position.

Complexity: O(|t|).

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        i = 0
        for ch in t:
            if i < len(s) and s[i] == ch:
                i += 1
        return i == len(s)