392. Is Subsequence 📏
Difficulty: Easy
- Tags: Two Pointers
, String
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. For example, "ace" is a subsequence of "abcde" while "aec" is not.
Examples 🌟
🔹 Example 1:
Input:
Output:
🔹 Example 2:
Input:
Output:
Constraints ⚙️
0 <= s.length <= 100
0 <= t.length <= 10^4
s
andt
consist only of lowercase English letters.
Solution 💡
Approach 1: Two-Pointer Technique
Initialize Two Pointers: Use one pointer for each string (
i
fors
andj
fort
).Traverse through
t
: Move through the characters oft
. If a character int
matches the current character ins
, move the pointer ins
to the next position.End Condition: If the pointer for
s
reaches the end ofs
, all characters ins
have been matched in order, so returntrue
. Otherwise, returnfalse
.
Java Solution
Time Complexity ⏳
O(n + m), where
n
is the length ofs
andm
is the length oft
. We traverse both strings once.
Space Complexity 💾
O(1), as no additional space is used.
Follow-up: Efficient Solution for Multiple Queries
If there are multiple s
strings (e.g., s1, s2, ..., sk
), consider Binary Search with Preprocessing:
Preprocess
t
: Create a map where each character points to a list of indices int
.Binary Search for Subsequences: For each
s
, use binary search to find each character’s position int
that comes after the previously matched character’s index.
You can find the full solution here.
Last updated