Is Subsequence – Solution & Complexity
1. Understand What Subsequence Means
sis a subsequence oftif all characters ofsappear intin the same order.- Characters in
tmay be skipped, but characters inscannot be reordered. - An empty
sis always a subsequence.
2. Think About a Direct Scan
- We do not need to generate all possible subsequences of
t. - Instead, scan
tfrom left to right and try to match the next needed character froms. - If every character from
sis matched, returnTrue.
3. Use Two Pointers
- Pointer
itracks the next character needed froms. - Pointer
jis the current position while scanningt. - When
s[i] == t[j], advancei; always continue scanning throught.
4. Handle Completion Early
- Once
ireacheslen(s), every character inshas been matched. - At that point we can return
Truewithout scanning the rest oft. - If the scan ends first, return whether all of
swas matched.
5. Final Complete Solution
- The scan preserves order because
tis processed left to right exactly once. - Time complexity is O(len(t)) and space complexity is O(1).
- The empty string case works naturally because
i == len(s)at the start.