Skip to content

392. Is Subsequence

Edited by Charles

Easy · Python · Array

Problem

Read the original problem on LeetCode.

The official page contains the problem statement, examples, and constraints.

Explanation, examples & other approaches

Core idea

Use two pointers:

  • i points to the current character in s
  • j points to the current character in t

Original study notes follow, including intermediate snippets and earlier attempts.

Problem

Given two strings s and t, return True if s is a subsequence of t, otherwise return False.

A subsequence is a string that can be derived from another string by deleting some characters without changing the relative order of the remaining characters.

Example

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

Output:
True
Input:
s = "axc"
t = "ahbgdc"

Output:
False

Approach: Two Pointers

Use two pointers:

  • i points to the current character in s
  • j points to the current character in t
s: a b c
   ↑
   i

t: a h b g d c
   ↑
   j

The pointer j always moves forward because we are searching through t.

The pointer i only moves forward when we successfully find s[i] in t.

Case 1: Characters Match

If:

s[i] == t[j]

we have found the current character of s, so move i forward:

i += 1

Case 2: Characters Do Not Match

If:

s[i] != t[j]

we still need to find s[i], so i stays unchanged.

We only move j forward to continue searching in t.

Therefore, j moves forward in every iteration:

j += 1

Example Walkthrough

s = "abc"
t = "ahbgdc"

Start:

s: a b c
   ↑
   i

t: a h b g d c
   ↑
   j

Step 1

a == a

Match:

i → b
j → h

Step 2

b != h

Keep i at b, move j:

i → b
j → b

Step 3

b == b

Match:

i → c
j → g

Step 4

c != g

Move j.

Step 5

c != d

Move j.

Step 6

c == c

Now all characters in s have been matched.

Therefore:

i == len(s)

and the answer is True.

Why return i == len(s)?

i represents how many characters of s have been successfully matched.

If:

i == len(s)

then every character in s has been found in t in the correct order.

Therefore, s is a subsequence of t.

Complexity

Let n = len(t).

  • Time: O(n)
  • Space: O(1)

Each character in t is visited at most once.

Key Idea

Pointer in t:
always moves forward

Pointer in s:
moves forward only when a match is found

In code:

if s[i] == t[j]:
    i += 1

j += 1

This preserves the relative order of characters in s, which is exactly what the definition of a subsequence requires.

Study record
Field Value
Attempts 1
Mastery ❚
The Latest Attempt October 3, 2026

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)

Back to Bonus Array · All Algorithm notes