Is Subsequence

Easy14 min

How does the scan match "ace" inside "abcde"?

1 / 6

candidate

text

Step 1 of 6.
Both pointers begin at a. The characters match, so the first requirement is satisfied.
  • current comparison
  • matched
While checking "ace" against "abcde", the required character is c and the current text character is b. Why must only the text pointer move?

In the implementation, i points to the next required character in s, and j points to the character currently being inspected in t.

1class Solution:
2 def isSubsequence(self, s: str, t: str) -> bool:
3 i = j = 0
4 while i < len(s) and j < len(t):
5 if s[i] == t[j]:
6 i += 1
7 j += 1
8
9 return i == len(s)
Time: O(n)Space: O(1)

Time is O(n), where n is the length of text. Each text character is inspected at most once, and the scan may stop earlier after every candidate character has been matched. The two indices use O(1) auxiliary space.