class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
S = len(s)
T = len(t)
if s == '': return True
if S > T: return False
j = 0
for i in range(T):
if t[i] == s[j]:
if j == S-1:
return True
j += 1
return False
# Time: O(T)
# Space: O(1)
The “Is Subsequence” problem is a popular coding question found on platforms like LeetCode.
It asks whether a given string s is a subsequence of another string t.
A subsequence is a series of characters that appear in the same relative order, but not necessarily contiguously.
For example, the string "abc" is a subsequence of "ahbgdc", because the characters a, b, and c appear in the correct order, even though there are other characters in between.
This problem is commonly used to test your understanding of string manipulation, two-pointer techniques, and greedy algorithms. It also appears in real-world applications, such as validating input sequences, matching patterns in data streams, or building recommendation engines that rely on partial matches.
To solve this efficiently, we use a two-pointer technique. Here's how it works:
j to 0 to track the current position in s.t using a second pointer.t matches the current character in s, increment j.j reaches the end of s, that means all characters in s were found in order—return true.j reaches the end of s, return false.
Let’s consider the example s = "abc" and t = "ahbgdc":
t[0] = 'a' matches s[0] → move j to 1t[1] = 'h' ≠s[1] → skipt[2] = 'b' matches s[1] → move j to 2t[3] = 'g' ≠s[2] → skipt[4] = 'd' ≠s[2] → skipt[5] = 'c' matches s[2] → j = 3, end of s
Since all characters in s were matched in order, we return true.
Here are a few important cases to keep in mind:
s is an empty string, return true – the empty string is a subsequence of any string.t is shorter than s, return false – it’s impossible for s to be a subsequence.
This algorithm runs in O(n) time, where n is the length of t. We only scan through each character of t once.
The space complexity is O(1) since we don’t use any additional data structures beyond a few variables.
The “Is Subsequence” problem is an excellent exercise in understanding how to use two pointers effectively. It combines string processing with a greedy strategy and is useful preparation for more complex problems involving subsequences, string searching, and pattern matching.