1 minute read

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., “ace” is a subsequence of “abcde” while “aec” is not).

Example 1:

Input: s = “abc”, t = “ahbgdc” Output: true Example 2:

Input: s = “axc”, t = “ahbgdc” Output: false

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isSubsequence = function (s, t) {
  let sPointer = 0;
  let tPointer = 0;

  while (sPointer < s.length && tPointer < t.length) {
    if (s[sPointer] === t[tPointer]) {
      sPointer++;
      tPointer++;
    } else {
      tPointer++;
    }
  }

  return sPointer === s.length;
};

The function uses two pointers, sPointer and tPointer, to traverse both s and t. While both pointers are within the bounds of their respective strings, the function compares the characters at the current positions.

If the characters match, both pointers are moved to the next characters in s and t. If the characters don’t match, only the pointer for t is moved to the next character.

The function continues until either the pointer for s reaches the end of s or the pointer for t reaches the end of t.

If the pointer for s reaches the end of s, it means that s is a subsequence of t, and the function returns true. Otherwise, it returns false.

Leave a comment