AlgoMaster Logo

Is Subsequence

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Two Pointers

Intuition:

To check whether a string s is a subsequence of t, we try to match the characters of s in order while scanning through t. We don’t need to modify either string or use extra space.

We use two pointers:

  • one pointer moves through s
  • the other moves through t

As we traverse t, we look for characters that match the current character in s. Whenever we find a match, we advance the pointer in s.

The pointer in t always moves because we are scanning the entire sequence.

If we manage to advance through all characters in s, then every character in s appears in the correct order in t, meaning s is a subsequence of t.

Steps:

  1. Initialize two pointers, i for tracking the current character in s and j for scanning through t
  2. Iterate over t using j.
  3. Whenever s[i] == t[j], increment i because we matched a character of s.
  4. Always increment j because we continue scanning t.
  5. If i reaches the length of s, it means all characters in s have been matched correctly in order within t.
  6. Return true if all characters of s were matched; otherwise return false.

Code: