Back to Problem
Official 789 views

Editorial: Is Subsequence

by admin ·

7

1 Intuition

Greedily match each character of s to its earliest occurrence in t.

2 Approach

Scan t with one pointer and advance a second pointer in s whenever characters match. s is a subsequence iff the second pointer reaches the end.

3 Complexity Analysis

Time O(|t|), Space O(1).

4 Solution Code

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

5 Code Walkthrough

The reference solution below implements the approach step by step.