A two-pointer approach to check if one string is a subsequence of another
The original problem is here.
read)compare)while and and condition.t[read] and s[compare].t pointer (read) always increases by $1$ at each step, because we are continually scanning through the longer string.s pointer (compare) only increases when there is a match against t (i.e., s[compare] == t[read]).t pointer (read) reaches the length of t (we’ve scanned the entire target string), ORs pointer (compare) reaches the length of s (we’ve successfully matched all characters in the target subsequence).s inside t in the correct relative order.s pointer equals the length of s (compare == len(s)).class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
compare = 0
read = 0
while read < len(t) and compare < len(s):
if t[read] == s[compare]:
compare +=1
read +=1
return compare==len(s)
compare and read), resulting in constant extra space.| Time Complexity: $O( | t | )$. In the worst-case scenario, we traverse the string t exactly once to find all matches or determine failure. |