22- Is Subsequence
The problem can be found at the following link: Question Link
My Approach
Initialize an integer variable
ito 0. This variable will be used to keep track of the current character index in strings.Iterate through each character
xin the stringtusing a loop.Inside the loop, compare the current character
xintwith the character at indexiin strings.If the characters match (i.e.,
xis equal tos[i]), increment theivariable by 1 to move to the next character in strings.Continue this process for all characters in string
t.After the loop, check if
iis equal to the length of strings. If it is, it means that all characters inshave been found intin the same order, so returntrue. Otherwise, returnfalsebecause not all characters inswere found intin the same order.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(1)
Code (C++)
class Solution {
public:
bool isSubsequence(string s, string t) {
int i = 0;
for (auto& x : t) {
if (x == s[i]) i++;
}
return (i == s.size() ? true : false);
}
};
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated
Was this helpful?