Hide sidebar

Is Subsequence

Is Subsequence

GreedyTwo Pointers
EasyLeetCode #392
10 min

Problem Statement

Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example

Example 1:

Input: s = "abc", t = "ahbgdc"

s: "abc", t: "ahbgdc"

Output: true

Output: true

Solution

The greedy approach is to use two pointers. One pointer for `s` and one for `t`. We iterate through `t` and if we find a character that matches the character at the `s` pointer, we advance the `s` pointer. If the `s` pointer reaches the end of `s`, then `s` is a subsequence of `t`.

Algorithm Steps

  • Initialize two pointers, `i` for `s` and `j` for `t`.
  • Iterate with the `j` pointer through `t`.
  • If `s[i]` matches `t[j]`, increment `i`.
  • If `i` equals the length of `s`, it means we have found all characters of `s` in `t` in the correct order.

Is Subsequence

Greedy with Two Pointers

Input: s = "abc", t = "ahbgdc"

Output: false

Progress1 / 1

Ready to start the visualization

s

a
b
c

t

a
h
b
g
d
c
Is Subsequence 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)