← Back to Leo Academy Masterclass

Problem #392: Is Subsequence

Easy Two Pointers

Intuition & Strategy Breakdown

Use two pointers (i for s, j for t). Advance j on every step, and advance i when s[i] == t[j]. Return true if i reaching len(s).

Python Solution

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

Java Solution

class Solution {
    public boolean isSubsequence(String s, String t) {
        int i = 0, j = 0;
        while (i < s.length() && j < t.length()) {
            if (s.charAt(i) == t.charAt(j)) {
                i++;
            }
            j++;
        }
        return i == s.length();
    }
}
Watch Interactive Video on Leo Academy Main App