Is A String a Substring of Another String?
Problem: Given two strings
sandt, returnTrueifsis a subsequence oft, orFalseotherwise.
Testing Function
| |
Brute Force Approach
A sequence implies that order matters. Therefore, we’ll be traversing t and checking
if we can find the characters of s in order. The order here helps and it immediately
makes me think that a two-pointer technique is a good fit. I think it is often helpful
to imagine what the brute force solution looks like. In this case, we’d be checking
every possible subsequence of t to see if it matches s.
This would look something like this:
| |
>>> Result: `brute_force` - Pass
The time complexity of the above brute-force approach solution is t and s. This is not great, but it does help provide us a baseline and, at the very worst, we have provided a working solution.
Two-Pointer Approach
As I mentioned earlier, my immediate reaction here is that we can use a two-pointer technique. To achieve this, we’ll initialise two pointers i and j to 0. We’ll then iterate over t and s using these pointers. If the characters at the current pointers match, we’ll increment j. Otherwise, we’ll increment i. If we manage to iterate over all of s, then s is a subsequence of t.
| |
>>> Result: `two_pointers` - Pass
The time complexity of the above approach is t. This is a significant improvement over the brute-force approach. Perhaps the bigger improvement is the storage complexity which, due to the use of two pointers, is