[LeetCode] Top Interview 150 Problems Solving # 392 Is Subsequence
![[LeetCode] Top Interview 150 Problems Solving # 392 Is Subsequence](https://cdn.hashnode.com/res/hashnode/image/upload/v1742995570790/d51c4c73-cf23-413f-8cca-ef2da016a252.png)
Understanding the Problem
Given strings s and t, it is to tell whether s is the subsequence to t. It is not finding if the characters in s exist in t. Well basically it is, but the sequence matters too.
# example
Input: s = "abc", t = "ahbgdc"
Output: true
Approach
This would require a for loop to check each character. The loop will go through t as it may or may not contain s.
Solution
I have declared idx and initialized it with 0, to start from the first index of s. If only c from the loop of t is identical to s[idx], add up one to idx to move to the next sequence of s.
But it needs checking if idx is at the end of s. If it is at the end of s, there is no further need for checking the characters anymore, thus just return True.
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
idx = 0
for c in t:
if idx >= len(s):
return True
elif c == s[idx]:
idx += 1
if idx == len(s):
return True
return False
Reflection
The fact that I was trying to solve this with sort() or set() was a bit hilarious, but it was worth trying to see many test cases that went wrong with my code. It had 0ms time complexity which I am satisfied with.
About the author
South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?
Comments
Join the discussionNo comments yet. Be the first to comment.




