392. Is Subsequence
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to determine if a string s is a subsequence of another string t. A subsequence is formed by deleting zero or more characters from the original string t while maintaining the relative order of the remaining characters. For instance, "ace" is a subsequence of "abcde", but "aec" is not.
Solution
Is Subsequence in Python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i = 0 # Pointer for s
j = 0 # Pointer for t
# Iterate through t to find characters of s
while i < len(s) and j < len(t):
# If characters match, move pointer for s
if s[i] == t[j]:
i += 1
# Always move pointer for t
j += 1
# If we have traversed all of s, it's a subsequence
return i == len(s)
Is Subsequence in Java
class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0; // Pointer for s
int j = 0; // Pointer for t
// Iterate through t to find characters of s
while (i < s.length() && j < t.length()) {
// If characters match, move pointer for s
if (s.charAt(i) == t.charAt(j)) {
i++;
}
// Always move pointer for t
j++;
}
// If we have traversed all of s, it's a subsequence
return i == s.length();
}
}
Is Subsequence in C++
class Solution {
public:
bool isSubsequence(string s, string t) {
int i = 0; // Pointer for s
int j = 0; // Pointer for t
// Iterate through t to find characters of s
while (i < s.length() && j < t.length()) {
// If characters match, move pointer for s
if (s[i] == t[j]) {
i++;
}
// Always move pointer for t
j++;
}
// If we have traversed all characters of s, it's a subsequence
return i == s.length();
}
};
Is Subsequence in TypeScript
function isSubsequence(s: string, t: string): boolean {
let i = 0; // Pointer for s
let j = 0; // Pointer for t
// Iterate through t to find characters of s
while (i < s.length && j < t.length) {
// If characters match, move pointer for s
if (s[i] === t[j]) {
i++;
}
// Always move pointer for t
j++;
}
// If we have traversed all of s, it's a subsequence
return i === s.length;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.