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:
s = "abc"
t = "ahbgdc"Output:
true🔹 Example 2:
Input:
s = "axc"
t = "ahbgdc"Output:
falseConstraints ⚙️
0 <= s.length <= 1000 <= t.length <= 10^4sandtconsist only of lowercase English letters.
Solution 💡
Approach 1: Two-Pointer Technique
Initialize Two Pointers: Use one pointer for each string (
iforsandjfort).Traverse through
t: Move through the characters oft. If a character intmatches the current character ins, move the pointer insto the next position.End Condition: If the pointer for
sreaches the end ofs, all characters inshave been matched in order, so returntrue. Otherwise, returnfalse.
Java Solution
public class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) {
i++;
}
j++;
}
return i == s.length();
}
}Time Complexity ⏳
O(n + m), where
nis the length ofsandmis 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 intthat comes after the previously matched character’s index.
You can find the full solution here.
Last updated
Was this helpful?