Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 27 Nov, 2022
Improve Article
Save Article

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.

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)

Recommended Practice

First String is a Subsequence of second by Recursion:

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

Below is the 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 check whether str1 is subsequence of str2 or not.
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 

Time Complexity: O(N), The recursion will call at most N times.
Auxiliary Space: O(N), Function call stack space

First String is a Subsequence of second using Two Pointers (Iterative):

The idea is to use two pointers, one pointer will start from start of str1 and another will start from start of str2. If current character on both the indexes are same then increment both pointers otherwise increment the pointer which is pointing str2.

Follow the steps below to solve the problem:

  • Initialize the pointers i and j with zero, where i is the pointer to str1 and j is the pointer to str2.
  • If str1[i] = str2[j] then increment both i and j by 1.
  • Otherwise, increment only j by 1.
  • If i reaches the end of str1 then return TRUE else return FALSE.

Below is the implementation of the above approach

C++




/*Iterative C++ program to check
If a string is subsequence of another string*/
  
#include <bits/stdc++.h>
using namespace std;
  
/*Returns true if s1 is subsequence of s2*/
bool issubsequence(string& s1, string& s2)
{
    int n = s1.length(), m = s2.length();
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (s1[i] == s2[j])
            i++;
        j++;
    }
    /*If i reaches end of s1,that mean we found all
    characters of s1 in s2,
    so s1 is subsequence of s2, else not*/
    return i == n;
}
int main()
  
{
    string s1 = "gksrek";
    string s2 = "geeksforgeeks";
    if (issubsequence(s1, s2))
        cout << "gksrek is subsequence of geekforgeeks" << endl;
    else
        cout << "gksrek is not a subsequence of geekforgeeks" << endl;
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
  
class GFG 
{
    
    /*Iterative Java program to check
If a String is subsequence of another String*/
  
/*Returns true if s1 is subsequence of s2*/
static boolean issubsequence(String s1, String s2)
{
    int n = s1.length(), m = s2.length();
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (s1.charAt(i) == s2.charAt(j))
            i++;
        j++;
    }
    /*If i reaches end of s1,that mean we found all
    characters of s1 in s2,
    so s1 is subsequence of s2, else not*/
    return i == n;
}
      
public static void main(String args[])
{
    String s1 = "gksrek";
    String s2 = "geeksforgeeks";
    if (issubsequence(s1, s2))
        System.out.println("gksrek is subsequence of geekforgeeks");
    else
        System.out.println("gksrek is not a subsequence of geekforgeeks");
}
}
  
// This code is contributed by shinjanpatra.


Python3




# Iterative JavaScript program to check
# If a string is subsequence of another string
  
# Returns true if s1 is subsequence of s2
def issubsequence(s1, s2):
  
    n,m = len(s1),len(s2)
    i,j = 0,0
    while (i < n and j < m):
        if (s1[i] == s2[j]):
            i += 1
        j += 1
      
    # If i reaches end of s1,that mean we found all
    # characters of s1 in s2,
    # so s1 is subsequence of s2, else not
    return i == n
  
  
# driver code
s1 = "gksrek"
s2 = "geeksforgeeks"
if (issubsequence(s1, s2)):
    print("gksrek is subsequence of geekforgeeks")
else:
    print("gksrek is not a subsequence of geekforgeeks")
  
# This code is contributed by shinjanpatra


C#




// C# code to implement the approach
using System;
  
class GFG {
  
  /*Returns true if s1 is subsequence of s2*/
  static bool issubsequence(string s1, string s2)
  {
    int n = s1.Length, m = s2.Length;
    int i = 0, j = 0;
    while (i < n && j < m) {
      if (s1[i] == s2[j])
        i++;
      j++;
    }
    /*If i reaches end of s1,that mean we found all
        characters of s1 in s2,
        so s1 is subsequence of s2, else not*/
    return i == n;
  }
  
  public static void Main(string[] args)
  {
    string s1 = "gksrek";
    string s2 = "geeksforgeeks";
    if (issubsequence(s1, s2))
      Console.WriteLine(s1 + " is subsequence of "
                        + s2);
    else
      Console.WriteLine(
      s1 + " is not a subsequence of " + s2);
  }
}
  
// This code is contributed by phasing17.


Javascript




<script>
  
/*Iterative JavaScript program to check
If a string is subsequence of another string*/
  
  
/*Returns true if s1 is subsequence of s2*/
function issubsequence(s1, s2)
{
    let n = s1.length, m = s2.length;
    let i = 0, j = 0;
    while (i < n && j < m) {
        if (s1[i] == s2[j])
            i++;
        j++;
    }
    /*If i reaches end of s1,that mean we found all
    characters of s1 in s2,
    so s1 is subsequence of s2, else not*/
    return i == n;
}
  
// driver code
  
let s1 = "gksrek";
let s2 = "geeksforgeeks";
if (issubsequence(s1, s2))
    document.write("gksrek is subsequence of geekforgeeks","</br>");
else
    document.write("gksrek is not a subsequence of geekforgeeks","</br>");
  
// This code is contributed by shinjanpatra
  
</script>


Output

gksrek is subsequence of geekforgeeks

Time Complexity: O(max(n,m)), where n,m are the length of given string s1 and s2 respectively. 
Auxiliary Space: O(1) 

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
Related Articles

Start Your Coding Journey Now!