#392
Is Subsequence
EasyTwo PointersStringDynamic ProgrammingTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using two pointers, we can efficiently check if 's' is a subsequence of 't' by iterating through both strings simultaneously. This method is much faster as it only requires a single pass through both strings.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one for 's' and one for 't'.
- 2Step 2: Traverse through 't' using its pointer.
- 3Step 3: If characters at both pointers match, move the pointer for 's' forward.
- 4Step 4: Always move the pointer for 't' forward.
- 5Step 5: If the pointer for 's' reaches the end of 's', return true; otherwise, return false.
solution.py8 lines
1# Full working Python code
2def isSubsequence(s, t):
3 s_ptr, t_ptr = 0, 0
4 while s_ptr < len(s) and t_ptr < len(t):
5 if s[s_ptr] == t[t_ptr]:
6 s_ptr += 1
7 t_ptr += 1
8 return s_ptr == len(s)ℹ
Complexity note: The time complexity is O(n) because we traverse each string at most once, making it linear in relation to the length of 't'. The space complexity is O(1) as we only use a few variables.
- 1Using two pointers can significantly reduce time complexity.
- 2Understanding subsequences helps in recognizing patterns in string problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.