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).
s
or t
is an empty string?
s
is empty, it is trivially a subsequence of t
, so return true
.t
is empty and s
is not, return false
since a non-empty string cannot be a subsequence of an empty string.s
and t
?
s
and t
consist only of lowercase English letters.s
and t
can be up to 10^4.s
(let’s call it i
) and one for t
(let’s call it j
).t
: Traverse the string t
using the pointer j
. Each time a character in t
matches the character in s
at pointer i
, increment i
.i
reaches the end of s
(i == s.length()
), it means all characters of s
have been matched in order in t
, so return true
. Otherwise, return false
.#include <iostream>
#include <string>
bool isSubsequence(const std::string& s, const std::string& t) {
int i = 0; // Pointer for s
int j = 0; // Pointer for t
while (i < s.length() && j < t.length()) {
if (s[i] == t[j]) {
i++;
}
j++;
}
return i == s.length();
}
int main() {
std::string s = "abc";
std::string t = "ahbgdc";
bool result = isSubsequence(s, t);
std::cout << std::boolalpha << result << std::endl; // Should print "true"
return 0;
}
n
is the length of s
and m
is the length of t
. This is because we perform at most one pass through each string.This solution is efficient and straightforward, making use of two-pointer technique which is appropriate given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?