AAlgoLoopSpaced repetition for LeetCode
EASYTwo PointersLeetCode ↗

Is Subsequence

The key idea

A subsequence keeps relative order but allows gaps. Walk t once with a pointer on s: every time t's current char matches s's next needed char, advance the s pointer. If the s pointer reaches the end, every char of s was matched in order.

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. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Constraints

Examples

Input: s = "abc", t = "ahbgdc" Output: true
Input: s = "axc", t = "ahbgdc" Output: false

Complexity

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

See the full solution

410310
Step-by-step visualization
Start free →

More Two Pointers problems