392. Is Subsequence
Asked at 13Meta44Amazon41Google39Microsoft39Bloomberg36Wix87Tinkoff86Pinterest67Yandex61Virtu Financial56Adobe44Zoho42Infosys39
Problem
Decide whether s is a subsequence of t: can s be obtained by deleting zero or more characters of t without reordering the rest?
Example: s = "abc", t = "ahbgdc" → true; s = "axc" → false
Constraints: follow-up: many different s queried against the same t.
Greedy match: advance in s whenever t[j] equals s[i]. Success if all of s is consumed.
Follow-up (many s queries): index positions of each char in t, then binary-search the next position.
Complexity: O(|t|).
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i = 0
for ch in t:
if i < len(s) and s[i] == ch:
i += 1
return i == len(s)
assert Solution().isSubsequence("abc", "ahbgdc") is True
assert Solution().isSubsequence("axc", "ahbgdc") is False
class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0;
for (int j = 0; j < t.length() && i < s.length(); j++)
if (s.charAt(i) == t.charAt(j)) i++;
return i == s.length();
}
}
func isSubsequence(s string, t string) bool {
i := 0
for j := 0; j < len(t) && i < len(s); j++ {
if s[i] == t[j] {
i++
}
}
return i == len(s)
}