Is Subsequence
- 28 Jul, 2025
๐ Problem Statement
โ Problem: Is Subsequence
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is formed by deleting some (or no) characters without changing the order of the remaining characters.
Examples:
-
Input:
s = "abc",t = "ahbgdc"
Output:true -
Input:
s = "axc",t = "ahbgdc"
Output:false
Constraints:
0 <= s.length <= 1000 <= t.length <= 10^4sandtconsist only of lowercase English letters
๐ง Problem Explanation
We need to check if all characters in string s appear in string t, in the same order, possibly with other characters in between.
๐ก Approach
- Use two pointers
ifortandjfors. - Move through both strings:
- If characters match, advance both
iandj. - If not, just advance
i(keep looking int).
- If characters match, advance both
- If
jreaches the end ofs, it means all characters ofswere matched int.
๐งพ Pseudocode
function: isSubsequence
params:
- s: str
- t: str
logic:
- if s is empty: return True
- if len(s) > len(t): return False
- initialize i = 0, j = 0
- while i < len(t):
- if s[j] == t[i]:
- increment j
- if j == len(s): return True
- increment i
- return False
โ Code
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
J = len(s)
I = len(t)
i, j = 0, 0
if s == '':
return True
if len(s) > len(t):
return False
while i < I:
if s[j] == t[i]:
if j == J - 1:
return True
j += 1
i += 1
return False
๐ Complexities
- Time Complexity:
O(n)โ wheren = len(t) - Space Complexity:
O(1)โ uses constant extra space
๐ Notes
- Pattern Used: Two Pointers
- Insights:
- Always advance through
t, matching characters withsas you go. j == len(s)at the end means we found all characters ofsin order insidet.- Edge case: an empty
sis always a subsequence of any stringt.
- Always advance through