LeetCode 75 Level 1 — Is Subsequence
Problem
Given two strings s
and t
, return true
if s
is a subsequence of t
, or false
otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace"
is a subsequence of "abcde"
while "aec"
is not).
Examples
- Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
- Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
Constraints
0 <= s.length <= 100
0 <= t.length <= 104
s
andt
consist only of lowercase English letters.
Solution
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s:
return True
if not t:
return False
sleft, sright = 0, len(s)
tleft, tright = 0, len(t)
while sleft < sright and tleft < tright:
if s[sleft] == t[tleft]:
sleft += 1
tleft += 1
return sleft == len(s)
Time and Space Complexity
- Time Complexity: O(t). Given t is the number of elements in string
t
. - Space Complexity: O(1). No auxiliary memory space used.
Takeaways
Thank you for reading this short problem solving question. If anyone knows a better or faster time complexity to solve this question, feel free to comment and feedback. Peace! ✌️
Level Up Coding
Thanks for being a part of our community! More content in the Level Up Coding publication.
Follow: Twitter, LinkedIn, Newsletter
Level Up is transforming tech recruiting ➡️ Join our talent collective