<AI/>
enru
Все статьи

Is subsequence

LeetCode 392: Check whether one string is a subsequence of another using two pointers.

Сложность
Легкая
Опубликовано
Темы
#string#two pointers
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given two strings s and t. Write a function that returns true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string formed from the original one by deleting some (possibly none) characters without changing the relative positions of the remaining characters (i.e. ace is a subsequence of abcde, while aec is not).

Constraints

  • The length of s is in the range from 0 to 100
  • The length of t is in the range from 0 to 10000
  • Both strings consist only of lowercase English letters

Examples

Input: s = "abc", t = "ahbgdc"

Answer: true

Solution

We'll use the simplest approach: walking through both strings with two pointers.

We loop over all characters of t and compare them with the characters of s. To track our position in s, we use the pointer pos.

  • If the characters match, we move pos one position forward.
  • If after going through all characters of t the pointer pos points to the end of s, then s is a subsequence of t.
  • If this condition becomes true during some iteration, we can exit early and return true, since there is no point in scanning the rest of t.
typescript
export const isSubsequence = (s: string, t: string): boolean => {
  let pos = 0;
 
  if (s === '') {
    return true;
  }
 
  for (let i = 0; i < t.length; i++) {
    const char = t[i];
 
    if (pos === s.length) {
      return true;
    }
 
    if (char === s[pos]) {
      pos++;
    }
  }
 
  return pos === s.length;
};

Complexity Analysis

Time Complexity

O(n), where n is the length of t.

Space Complexity

O(1), since we use a constant amount of memory for variables.