Is Subsequence
Easy
Topics
Given two strings s and t, return true if s is a subsequence of t (formed by deleting some characters of t without changing the order of the rest).
Example 1
s
t
The shaded characters of
t spell s in order, though not contiguously — so the answer is true.Rows are the two strings; shaded cells in t are the greedy match for s.
Input: s = "abc", t = "ahbgdc" Output: true
Example 2
s
t
Scanning forward through
t runs out of string before matching all of s, so the answer is false.Input: s = "axc", t = "ahbgdc" Output: false
Constraints
- 0 <= s.length <= 100
- 0 <= t.length <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Greedily match the characters of s against t in order. Advance through t; whenever it matches the current needed character of s, move to the next needed character. If we consume all of s, it is a subsequence.
Approach
- Pointer
iintos. - Walk
t; whent[j] == s[i], advancei. - If
ireaches the end ofs, return True.
Walkthrough
s = "abc", t = "ahbgdc"
a matches a, b matches b, c matches c -> consumed all of s -> trueComplexity
- Time — O(|t|): one pass over t.
- Space — O(1): two indices.
Common Pitfalls
- An empty
sis a subsequence of anything — the pointer starts already "consumed".
Full Solution — all languages
class Solution:
def isSubsequence(self, s, t):
it = iter(t)
return all(c in it for c in s)import java.util.*;
class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0;
for (int j = 0; j < t.length() && i < s.length(); j++) if (s.charAt(i) == t.charAt(j)) i++;
return i == s.length();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isSubsequence(string s, string t) {
int i = 0;
for (int j = 0; j < (int)t.size() && i < (int)s.size(); j++) if (s[i] == t[j]) i++;
return i == (int)s.size();
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var isSubsequence = function(s, t) {
let i = 0;
for (let j = 0; j < t.length && i < s.length; j++) if (s[i] === t[j]) i++;
return i === s.length;
};