Is Subsequence

Determine if s is a subsequence of t using a single greedy two-pointer walk.

Easy
Time O(n + m) Space O(1)
LeetCode
2 min read
two-pointers string

Problem#

Return true if s is a subsequence of t — i.e., s can be formed by deleting zero or more characters from t without reordering.

Examples#

  • s = "abc", t = "ahbgdc"true
  • s = "axc", t = "ahbgdc"false

Constraints#

  • 0 <= s.length <= 100, 0 <= t.length <= 10^4.

Approach#

Walk both with two pointers; advance i over s only on match, advance j over t every step. Subsequence iff i reaches the end of s.

Solution#

Is Subsequence
class Solution {
public:
bool isSubsequence(string s, string t) {
int i = 0;
for (char c : t) {
if (i < (int)s.size() && s[i] == c) ++i;
}
return i == (int)s.size();
}
};

Editorial#

Greedy is optimal here: a deferred match in t never helps. The early-exit version (returning true as soon as i == s.size()) is a constant-factor speedup but doesn’t change asymptotics. For the follow-up where many s values are checked against the same t, precomputing per-character next-occurrence arrays drops each query to O(|s| log |t|).

Complexity#

  • Time: O(|t|).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.