|
| 1 | +# Is Subsequence |
| 2 | + |
| 3 | +Given two strings s and t, return true if s is a subsequence of t, or false otherwise. |
| 4 | + |
| 5 | +A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the |
| 6 | +characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of " |
| 7 | +abcde" while "aec" is not). |
| 8 | + |
| 9 | +``` plain |
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Input: s = "abc", t = "ahbgdc" |
| 13 | +Output: true |
| 14 | +Example 2: |
| 15 | +
|
| 16 | +Input: s = "axc", t = "ahbgdc" |
| 17 | +Output: false |
| 18 | +``` |
| 19 | + |
| 20 | +## Related Topics |
| 21 | + |
| 22 | +- Two Pointers |
| 23 | +- String |
| 24 | +- Dynamic Programming |
| 25 | + |
| 26 | + |
| 27 | +### Solution |
| 28 | + |
| 29 | +The key intuition behind this problem is that we can use two pointers to match characters of s in t from left to right. |
| 30 | +We maintain a first pointer for string s and a second pointer for string t. As we scan through t, whenever the current |
| 31 | +character in t matches the current character we're looking for in s, we advance the first pointer to look for the next |
| 32 | +character. We always advance the second pointer regardless of a match. If by the end of the traversal the first pointer |
| 33 | +has reached the end of s, it means every character in s was found in t in the correct relative order, so s is a |
| 34 | +subsequence of t. |
| 35 | + |
| 36 | +Now, let’s look at the solution steps below: |
| 37 | + |
| 38 | +1. Initialize a pointer sPointer (pointing to the start of s) to 0 |
| 39 | +2. Initialize a pointer tPointer (pointing to the start of t) to 0 |
| 40 | +3. Iterate using a while loop as long as `pointer_s` is less than the length of s and `pointer_t` is less than the length |
| 41 | + of t. |
| 42 | + - If the character at `s[pointer_s]` equals the character at `t[pointer_t]`, |
| 43 | + - Increment `pointer_s` by 1 |
| 44 | + - Regardless of whether there was a match, increment `pointer_t` by 1 to continue scanning through t. |
| 45 | +4. After the loop terminates, check if sPointer equals the length of s. If it does, all characters of s have been |
| 46 | + matched in order within t, so return TRUE. Otherwise, return FALSE. |
| 47 | + |
| 48 | +#### Complexity analysis |
| 49 | + |
| 50 | +##### Time complexity |
| 51 | + |
| 52 | +The time complexity of the solution is O(n) where n is the length of t. In the worst case, we traverse the entire string |
| 53 | +t once with tPointer, performing a constant-time character comparison at each step. |
| 54 | + |
| 55 | +##### Space complexity |
| 56 | + |
| 57 | +The space complexity of the solution is O(1) because we only use two integer pointer variables (sPointer and tPointer) |
| 58 | +regardless of the input size. No additional data structures are allocated. |
0 commit comments