Is Subsequence — LeetCode 392 Python Solution

EasyTwo PointersStringDynamic Programming
Problem
#392
Reading time
2 min

The problem

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.

Example

Input
s = "abc", t = "ahbgdc"
Output
true

Python solution

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

Complexity

MeasureComplexity
TimeO(m + n), where m and n are the lengths of the strings s and t respectively
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 392. Is Subsequence is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On study lists

This problem is on LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 392. Is Subsequence?
LeetCode 392. Is Subsequence is rated Easy on LeetCode.
What is the time complexity of LeetCode 392. Is Subsequence?
The Python solution on this page runs in O(m + n), where m and n are the lengths of the strings s and t respectively.
What is the space complexity of LeetCode 392. Is Subsequence?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 392. Is Subsequence cover?
LeetCode 392. Is Subsequence is tagged Two Pointers, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview