Is Subsequence

String, Two Pointers

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

Constraints:

  • 0 <= s.length <= 100

  • 0 <= t.length <= 104

  • s and t consist only of lowercase English letters.

Solutions

Approach - Two Pointers Technique

This algorithm checks if string s is a subsequence of string t. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Steps

  1. Initialize two pointers i and j to 0. i is used to traverse string s and j is used to traverse string t. Also, initialize a counter found to 0 which keeps track of the number of characters of s found in t.

  2. Start a while loop that continues as long as i is less than the length of s and j is less than the length of t.

  3. Inside the loop, check if the j-th character of t is equal to the i-th character of s. If it is, increment both i and found.

  4. Regardless of whether the characters match, increment j to move to the next character in t.

  5. After the loop ends, check if found is equal to the length of s. If it is, return true, indicating that s is a subsequence of t. If not, return false.

public class Solution {
    public bool IsSubsequence(string s, string t) {
        
        int j =0;
        int i=0;
         int found=0;
            while(i<s.Length && j<t.Length){
                if(t[j]==s[i]){
                    i++;
                    found++;
                }
                j++;
            }
        return found==s.Length;
    }
}

Complexity

  • Time complexity: O(n) where n is the length of t string.

  • Space complexity: O(1)

Last updated