easy
Is Subsequence
Link to algo
The problem Is Subsequence is defined as follows: 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 changing the relative order of the remaining characters.
Here's a possible solution to this problem in JavaScript:
function isSubsequence(s, t) {
let i = 0;
let j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) {
i++;
}
j++;
}
return i === s.length;
}
The above function uses two pointers i and j to iterate over the characters of s and t respectively. The while loop continues until either i reaches the end of s or j reaches the end of t. At each iteration, if the current characters of s and t match, i is incremented to move to the next character of s. Otherwise, j is incremented to move to the next character of t.
Finally, the function checks if i has reached the end of s. If yes, it means that all the characters of s have been found in t in the same order, so the function returns true. Otherwise, it means that at least one character of s is missing in t, so the function returns false.
The time complexity of this solution is O(n), where n is the length of t. The reason is that the function iterates over all the characters of t at most once, and each iteration takes constant time. The space complexity is O(1), because the function uses only a constant amount of additional memory regardless of the size of the input.