Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Given two strings, find if first string is a subsequence of second

  • Difficulty Level : Easy
  • Last Updated : 17 May, 2022

Given two strings str1 and str2, find if str1 is a subsequence of str2. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements (source: wiki). The expected time complexity is linear.

Examples : 

Input: str1 = "AXY", str2 = "ADXCPY"
Output: True (str1 is a subsequence of str2)

Input: str1 = "AXY", str2 = "YADXCP"
Output: False (str1 is not a subsequence of str2)

Input: str1 = "gksrek", str2 = "geeksforgeeks"
Output: True (str1 is a subsequence of str2)

The idea is simple, we traverse both strings from one side to another side (say from rightmost character to leftmost). If we find a matching character, we move ahead in both strings. Otherwise, we move ahead only in str2. 

Following is a Recursive Implementation of the above idea.  

C++




// Recursive C++ program to check
// if a string is subsequence
// of another string
#include <cstring>
#include <iostream>
using namespace std;
 
// Returns true if str1[] is a
// subsequence of str2[]. m is
// length of str1 and n is length of str2
bool isSubSequence(char str1[], char str2[], int m, int n)
{
 
    // Base Cases
    if (m == 0)
        return true;
    if (n == 0)
        return false;
 
    // If last characters of two
    // strings are matching
    if (str1[m - 1] == str2[n - 1])
        return isSubSequence(str1, str2, m - 1, n - 1);
 
    // If last characters are
    // not matching
    return isSubSequence(str1, str2, m, n - 1);
}
 
// Driver program to test methods of graph class
int main()
{
    char str1[] = "gksrek";
    char str2[] = "geeksforgeeks";
    int m = strlen(str1);
    int n = strlen(str2);
    isSubSequence(str1, str2, m, n) ? cout << "Yes "
                                    : cout << "No";
    return 0;
}


Java




// Recursive Java program to check if a string
// is subsequence of another string
import java.io.*;
 
class SubSequence {
    // Returns true if str1[] is a subsequence of str2[]
    // m is length of str1 and n is length of str2
    static boolean isSubSequence(String str1, String str2,
                                 int m, int n)
    {
        // Base Cases
        if (m == 0)
            return true;
        if (n == 0)
            return false;
 
        // If last characters of two strings are matching
        if (str1.charAt(m - 1) == str2.charAt(n - 1))
            return isSubSequence(str1, str2, m - 1, n - 1);
 
        // If last characters are not matching
        return isSubSequence(str1, str2, m, n - 1);
    }
 
    // Driver program
    public static void main(String[] args)
    {
        String str1 = "gksrek";
        String str2 = "geeksforgeeks";
        int m = str1.length();
        int n = str2.length();
        boolean res = isSubSequence(str1, str2, m, n);
        if (res)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// Contributed by Pramod Kumar


Python3




# Recursive Python program to check
# if a string is subsequence
# of another string
 
# Returns true if str1[] is a
# subsequence of str2[].
 
 
def isSubSequence(string1, string2, m, n):
    # Base Cases
    if m == 0:
        return True
    if n == 0:
        return False
 
    # If last characters of two
    # strings are matching
    if string1[m-1] == string2[n-1]:
        return isSubSequence(string1, string2, m-1, n-1)
 
    # If last characters are not matching
    return isSubSequence(string1, string2, m, n-1)
 
 
# Driver program to test the above function
string1 = "gksrek"
string2 = "geeksforgeeks"
 
if isSubSequence(string1, string2, len(string1), len(string2)):
    print ("Yes")
else:
    print ("No")
 
# This code is contributed by BHAVYA JAIN


C#




// Recursive C# program to check if a string
// is subsequence of another string
using System;
 
class GFG {
 
    // Returns true if str1[] is a
    // subsequence of str2[] m is
    // length of str1 and n is length
    // of str2
    static bool isSubSequence(string str1, string str2,
                              int m, int n)
    {
 
        // Base Cases
        if (m == 0)
            return true;
        if (n == 0)
            return false;
 
        // If last characters of two strings
        // are matching
        if (str1[m - 1] == str2[n - 1])
            return isSubSequence(str1, str2, m - 1, n - 1);
 
        // If last characters are not matching
        return isSubSequence(str1, str2, m, n - 1);
    }
 
    // Driver program
    public static void Main()
    {
        string str1 = "gksrek";
        string str2 = "geeksforgeeks";
        int m = str1.Length;
        int n = str2.Length;
        bool res = isSubSequence(str1, str2, m, n);
 
        if (res)
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// Recursive PHP program to check
// if a string is subsequence of
// another string
 
// Returns true if str1[] is a
// subsequence of str2[]. m is
// length of str1 and n is
// length of str2
 
function isSubSequence($str1, $str2,
                             $m, $n)
{
    // Base Cases
    if ($m == 0) return true;
    if ($n == 0) return false;
 
    // If last characters of two
    // strings are matching
    if ($str1[$m - 1] == $str2[$n - 1])
        return isSubSequence($str1, $str2,
                          $m - 1, $n - 1);
 
    // If last characters
    // are not matching
    return isSubSequence($str1, $str2,
                          $m, $n - 1);
}
 
// Driver Code
$str1= "gksrek";
$str2 = "geeksforgeeks";
$m = strlen($str1);
$n = strlen($str2);
 
$t = isSubSequence($str1, $str2, $m, $n) ?
                                   "Yes ":
                                     "No";
 
if($t = true)
    echo "Yes";
else
    echo "No";
 
// This code is contributed by ajit
?>


Javascript




<script>
 
// Recursive Javascript program to check if
// a string is subsequence of another string
 
// Returns true if str1[] is a
// subsequence of str2[] m is
// length of str1 and n is length
// of str2
function isSubSequence(str1, str2, m, n)
{
     
    // Base Cases
    if (m == 0)
        return true;
    if (n == 0)
        return false;
          
    // If last characters of two strings
    // are matching
    if (str1[m - 1] == str2[n - 1])
        return isSubSequence(str1, str2,
                             m - 1, n - 1);
 
    // If last characters are not matching
    return isSubSequence(str1, str2, m, n - 1);
}
 
// Driver code
let str1 = "gksrek";
let str2 = "geeksforgeeks";
let m = str1.length;
let n = str2.length;
let res = isSubSequence(str1, str2, m, n);
 
if (res)
    document.write("Yes");
else
    document.write("No");
     
// This code is contributed by divyesh072019
 
</script>


Output

Yes 

Memoization Technique

Here the idea is to check whether the size of the longest common subsequence is equal to the size of str1. If it’s equal it means there is a subsequence that exists in str2. Below is the implementation using the memoization technique. 

C++




// memoization C++ program to check
// if a string is subsequence
// of another string
#include <bits/stdc++.h>
using namespace std;
 
int dp[1001][1001];
 
// returns the length of longest common subsequence
int isSubSequence(string& s1, string& s2, int i, int j)
{
    if (i == 0 || j == 0) {
        return 0;
    }
    if (dp[i][j] != -1) {
        return dp[i][j];
    }
    if (s1[i - 1] == s2[j - 1]) {
        return dp[i][j]
               = 1 + isSubSequence(s1, s2, i - 1, j - 1);
    }
    else {
        return dp[i][j] = isSubSequence(s1, s2, i, j - 1);
    }
}
 
/* Driver program to test above function */
int main()
{
    string str1 = "gksrek";
    string str2 = "geeksforgeeks";
    int m = str1.size();
    int n = str2.size();
    if (m > n) {
        cout << "NO" << endl;
        return 0;
    }
    dp[m][n];
    memset(dp, -1, sizeof(dp));
    if (isSubSequence(str1, str2, m, n) == m) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
    return 0;
}
// this code is contributed by Arun Bang


Java




// memoization Java program to check
// if a string is subsequence
// of another string
class GFG {
 
  public static int[][] dp = new int[1001][1001];
 
  // returns the length of longest common subsequence
  public static int isSubSequence(String s1, String s2,
                                  int i, int j)
  {
    if (i == 0 || j == 0) {
      return 0;
    }
    if (dp[i][j] != -1) {
      return dp[i][j];
    }
    if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
      return dp[i][j]
        = 1 + isSubSequence(s1, s2, i - 1, j - 1);
    }
    else {
      return dp[i][j]
        = isSubSequence(s1, s2, i, j - 1);
    }
  }
 
  /* Driver program to test above function */
  public static void main(String[] args)
  {
    String str1 = "gksrek";
    String str2 = "geeksforgeeks";
    int m = str1.length();
    int n = str2.length();
    if (m > n) {
      System.out.println("NO");
    }
    for (int i = 0; i <= 1000; i++) {
      for (int j = 0; j <= 1000; j++)
        dp[i][j] = -1;
    }
    if (isSubSequence(str1, str2, m, n) == m) {
      System.out.println("YES");
    }
 
    else {
      System.out.println("NO");
    }
  }
}
 
// This code is contributed by phasing17


Python3




# memoization Python program to check
# if a string is subsequence
# of another string
dp = [[-1]*1001]*1001
 
# returns the length of longest common subsequence
def isSubSequence(s1,s2,i,j):
 
   if (i == 0 or j == 0):
      return 0
 
   if (dp[i][j] != -1):
      return dp[i][j]
 
   if (s1[i - 1] == s2[j - 1]):
      dp[i][j] = 1 + isSubSequence(s1, s2, i - 1, j - 1)
      return dp[i][j]
 
   else:
      dp[i][j] = isSubSequence(s1, s2, i, j - 1)
      return dp[i][j]
 
# Driver program to test above function
str1 = "gksrek"
str2 = "geeksforgeeks"
m = len(str1)
n = len(str2)
 
if (m > n):
   print("NO")
 
if (isSubSequence(str1, str2, m, n) == m):
    print("YES")
 
else:
    print("NO")
 
# this code is contributed by shinjanpatra


C#




// memoization C# program to check
// if a string is subsequence
// of another string
 
using System;
 
public class GFG {
    public static int[, ] dp = new int[1001, 1001];
 
    // returns the length of longest common subsequence
    public static int isSubSequence(string s1, string s2,
                                    int i, int j)
    {
        if (i == 0 || j == 0) {
            return 0;
        }
        if (dp[i, j] != -1) {
            return dp[i, j];
        }
        if (s1[i - 1] == s2[j - 1]) {
            return dp[i, j]
                = 1 + isSubSequence(s1, s2, i - 1, j - 1);
        }
        else {
            return dp[i, j]
                = isSubSequence(s1, s2, i, j - 1);
        }
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str1 = "gksrek";
        string str2 = "geeksforgeeks";
        int m = str1.Length;
        int n = str2.Length;
        if (m > n) {
            Console.WriteLine("NO");
        }
        for (int i = 0; i <= 1000; i++) {
            for (int j = 0; j <= 1000; j++)
                dp[i, j] = -1;
        }
        if (isSubSequence(str1, str2, m, n) == m) {
            Console.WriteLine("YES");
        }
 
        else {
            Console.WriteLine("NO");
        }
    }
}
 
// This code is contributed by phasing17


Javascript




<script>
    // memoization JavaScript program to check
    // if a let is subsequence
    // of another let
 
    let dp = new Array(1001).fill(-1).map(() => new Array(1001).fill(-1));
 
    // returns the length of longest common subsequence
    const isSubSequence = (s1, s2, i, j) => {
        if (i == 0 || j == 0) {
            return 0;
        }
        if (dp[i][j] != -1) {
            return dp[i][j];
        }
        if (s1[i - 1] == s2[j - 1]) {
            return dp[i][j]
                = 1 + isSubSequence(s1, s2, i - 1, j - 1);
        }
        else {
            return dp[i][j] = isSubSequence(s1, s2, i, j - 1);
        }
    }
 
    /* Driver program to test above function */
 
    let str1 = "gksrek";
    let str2 = "geeksforgeeks";
    let m = str1.length;
    let n = str2.length;
    if (m > n)
        document.write("NO<br/>");
 
    if (isSubSequence(str1, str2, m, n) == m) {
        document.write("YES<br/>");
    }
    else {
        document.write("NO<br/>");
    }
 
// This code is contributed by rakeshsahni
 
</script>


Output

YES

Time complexity: O(m*n)

Following is the Iterative Implementation

C++




// Iterative C++ program to check
// if a string is subsequence
// of another string
#include <cstring>
#include <iostream>
using namespace std;
 
// Returns true if str1[] is a
// subsequence of str2[]. m is
// length of str1 and n is length of str2
bool isSubSequence(char str1[], char str2[], int m, int n)
{
    int j = 0; // For index of str1 (or subsequence
 
    // Traverse str2 and str1, and
    // compare current character
    // of str2 with first unmatched char
    // of str1, if matched
    // then move ahead in str1
    for (int i = 0; i < n && j < m; i++)
        if (str1[j] == str2[i])
            j++;
 
    // If all characters of str1 were found in str2
    return (j == m);
}
 
// Driver program to test methods of graph class
int main()
{
    char str1[] = "gksrek";
    char str2[] = "geeksforgeeks";
    int m = strlen(str1);
    int n = strlen(str2);
    isSubSequence(str1, str2, m, n) ? cout << "Yes "
                                    : cout << "No";
    return 0;
}


Java




// Iterative Java program to check if a string
// is subsequence of another string
import java.io.*;
 
class GFG {
 
    // Returns true if str1[] is a subsequence
    // of str2[] m is length of str1 and n is
    // length of str2
    static boolean isSubSequence(String str1, String str2,
                                 int m, int n)
    {
        int j = 0;
 
        // Traverse str2 and str1, and compare
        // current character of str2 with first
        // unmatched char of str1, if matched
        // then move ahead in str1
        for (int i = 0; i < n && j < m; i++)
            if (str1.charAt(j) == str2.charAt(i))
                j++;
 
        // If all characters of str1 were found
        // in str2
        return (j == m);
    }
 
    // Driver program to test methods of
    // graph class
    public static void main(String[] args)
    {
        String str1 = "gksrek";
        String str2 = "geeksforgeeks";
        int m = str1.length();
        int n = str2.length();
        boolean res = isSubSequence(str1, str2, m, n);
 
        if (res)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Pramod Kumar


Python3




# Iterative Python program to check if a
# string is subsequence of another string
 
# Returns true if str1 is a subsequence of str2
 
 
def isSubSequence(str1, str2):
    m = len(str1)
    n = len(str2)
 
    j = 0    # Index of str1
    i = 0    # Index of str2
 
    # Traverse both str1 and str2
    # Compare current character of str2 with
    # first unmatched character of str1
    # If matched, then move ahead in str1
 
    while j < m and i < n:
        if str1[j] == str2[i]:
            j = j+1
        i = i + 1
 
    # If all characters of str1 matched,
    # then j is equal to m
    return j == m
 
# Driver Program
 
 
str1 = "gksrek"
str2 = "geeksforgeeks"
 
print ("Yes" if isSubSequence(str1, str2) else "No")
 
# Contributed by Harshit Agrawal


C#




// Iterative C# program to check if a string
// is subsequence of another string
using System;
 
class GFG {
 
    // Returns true if str1[] is a subsequence
    // of str2[] m is length of str1 and n is
    // length of str2
    static bool isSubSequence(string str1, string str2,
                              int m, int n)
    {
        int j = 0;
 
        // Traverse str2 and str1, and compare
        // current character of str2 with first
        // unmatched char of str1, if matched
        // then move ahead in str1
        for (int i = 0; i < n && j < m; i++)
            if (str1[j] == str2[i])
                j++;
 
        // If all characters of str1 were found
        // in str2
        return (j == m);
    }
 
    // Driver program to test methods of
    // graph class
    public static void Main()
    {
        String str1 = "gksrek";
        String str2 = "geeksforgeeks";
        int m = str1.Length;
        int n = str2.Length;
        bool res = isSubSequence(str1, str2, m, n);
 
        if (res)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by anuj_67.


PHP




<?php
// Iterative PHP program to check if
// a string is subsequence of another
// string
 
// Returns true if str1[] is
// a subsequence of str2[].
// m is length of str1 and n
// is length of str2
function isSubSequence($str1, $str2,
                             $m, $n)
{
    // For index of str1
    $j = 0;
     
    // Traverse str2 and str1,
    // and compare current
    // character of str2 with
    // first unmatched char of
    // str1, if matched then
    // move ahead in str1
    for($i = 0; $i < $n and
        $j < $m; $i++)
        if ($str1[$j] == $str2[$i])
            $j++;
     
    // If all characters of
    // str1 were found in str2
    return ($j == $m);
}
 
    // Driver Code
    $str1 = "gksrek";
    $str2 = "geeksforgeeks";
    $m = strlen($str1);
    $n = strlen($str2);
     
    if(isSubSequence($str1, $str2, $m, $n))
        echo "Yes ";
    else
        echo "No";
 
// This code is contributed by anuj_67.
?>


Javascript




<script>
    // Iterative Javascript program to check if a string
    // is subsequence of another string
     
    // Returns true if str1[] is a subsequence
    // of str2[] m is length of str1 and n is
    // length of str2
    function isSubSequence(str1, str2, m, n)
    {
        let j = 0;
          
        // Traverse str2 and str1, and compare
        // current character of str2 with first
        // unmatched char of str1, if matched
        // then move ahead in str1
        for (let i = 0; i < n && j < m; i++)
            if (str1[j] == str2[i])
                j++;
  
        // If all characters of str1 were found
        // in str2
        return (j == m);
    }
     
    let str1 = "gksrek";
    let str2 = "geeksforgeeks";
    let m = str1.length;
    let n = str2.length;
    let res = isSubSequence(str1, str2, m, n);
 
    if(res)
      document.write("Yes");
    else
      document.write("No");
     
    // This code is contributed by decode2207.
</script>


Output

Yes 

The Time Complexity of the implementation above is O(n) where n is the length of str2. 

Asked in: Accolite,Tesco
 

This article is contributed by Sachin Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!