Is Subsequence
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).
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: trueExample 2:
Input: s = "axc", t = "ahbgdc"
Output: false
Constraints:
0 <= s.length <= 1000 <= t.length <= 104sandtconsist only of lowercase English letters.
Solutions
Approach - Two Pointers Technique
This algorithm checks if string s is a subsequence of string t. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Steps
Initialize two pointers
iandjto 0.iis used to traverse stringsandjis used to traverse stringt. Also, initialize a counterfoundto 0 which keeps track of the number of characters ofsfound int.Start a
whileloop that continues as long asiis less than the length ofsandjis less than the length oft.Inside the loop, check if the
j-th character oftis equal to thei-th character ofs. If it is, increment bothiandfound.Regardless of whether the characters match, increment
jto move to the next character int.After the loop ends, check if
foundis equal to the length ofs. If it is, returntrue, indicating thatsis a subsequence oft. If not, returnfalse.
public class Solution {
public bool IsSubsequence(string s, string t) {
int j =0;
int i=0;
int found=0;
while(i<s.Length && j<t.Length){
if(t[j]==s[i]){
i++;
found++;
}
j++;
}
return found==s.Length;
}
}Complexity
Time complexity: O(n) where
nis the length oftstring.Space complexity: O(1)
Last updated