Given two strings str1 and str2, find if the first string is a Subsequence of the second string, i.e. 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)
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++
#include <cstring>
#include <iostream>
using namespace std;
bool isSubSequence( char str1[], char str2[], int m, int n)
{
if (m == 0)
return true ;
if (n == 0)
return false ;
if (str1[m - 1] == str2[n - 1])
return isSubSequence(str1, str2, m - 1, n - 1);
return isSubSequence(str1, str2, m, n - 1);
}
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
import java.io.*;
class SubSequence {
static boolean isSubSequence(String str1, String str2,
int m, int n)
{
if (m == 0 )
return true ;
if (n == 0 )
return false ;
if (str1.charAt(m - 1 ) == str2.charAt(n - 1 ))
return isSubSequence(str1, str2, m - 1 , n - 1 );
return isSubSequence(str1, str2, m, n - 1 );
}
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" );
}
}
|
Python3
def isSubSequence(string1, string2, m, n):
if m = = 0 :
return True
if n = = 0 :
return False
if string1[m - 1 ] = = string2[n - 1 ]:
return isSubSequence(string1, string2, m - 1 , n - 1 )
return isSubSequence(string1, string2, m, n - 1 )
string1 = "gksrek"
string2 = "geeksforgeeks"
if isSubSequence(string1, string2, len (string1), len (string2)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isSubSequence( string str1, string str2,
int m, int n)
{
if (m == 0)
return true ;
if (n == 0)
return false ;
if (str1[m - 1] == str2[n - 1])
return isSubSequence(str1, str2, m - 1, n - 1);
return isSubSequence(str1, str2, m, n - 1);
}
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" );
}
}
|
Javascript
<script>
function isSubSequence(str1, str2, m, n)
{
if (m == 0)
return true ;
if (n == 0)
return false ;
if (str1[m - 1] == str2[n - 1])
return isSubSequence(str1, str2,
m - 1, n - 1);
return isSubSequence(str1, str2, m, n - 1);
}
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" );
</script>
|
PHP
<?php
function isSubSequence( $str1 , $str2 ,
$m , $n )
{
if ( $m == 0) return true;
if ( $n == 0) return false;
if ( $str1 [ $m - 1] == $str2 [ $n - 1])
return isSubSequence( $str1 , $str2 ,
$m - 1, $n - 1);
return isSubSequence( $str1 , $str2 ,
$m , $n - 1);
}
$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" ;
?>
|
Time Complexity: O(N), The recursion will call at most N times.
Auxiliary Space: O(1), Function call stack space, because it is a tail recursion.
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++
#include <bits/stdc++.h>
using namespace std;
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++;
}
return i == n;
}
int main()
{
string s1 = "gksrek" ;
string s2 = "geeksforgeeks" ;
if (issubsequence(s1, s2))
cout << "gksrek is subsequence of geeksforgeeks"
<< endl;
else
cout << "gksrek is not a subsequence of "
"geeksforgeeks"
<< endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
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++;
}
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" );
}
}
|
Python3
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
return i = = n
s1 = "gksrek"
s2 = "geeksforgeeks"
if (issubsequence(s1, s2)):
print ( "gksrek is subsequence of geekforgeeks" )
else :
print ( "gksrek is not a subsequence of geekforgeeks" )
|
C#
using System;
class GFG {
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++;
}
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);
}
}
|
Javascript
<script>
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++;
}
return i == n;
}
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>" );
</script>
|
Outputgksrek is subsequence of geeksforgeeks
Time Complexity: O(max(n,m)), where n,m is the length of given string s1 and s2 respectively.
Auxiliary Space: O(1)
Another Approach for First String is a Subsequence of second using Queue:
Strategy: Use Queue to store the shorter string, pop one element at a time from queue and check if there’s a match in the longer string
proceed with poping elements only if theres a match, if Queue is empty at the end, we have a match.
C++
#include <bits/stdc++.h>
using namespace std;
bool issubsequence(string& s, string& t)
{
queue< char > q;
int cnt = 0;
for ( int i = 0; i < t.size(); i++) {
q.push(t[i]);
}
int i = 0;
while (!q.empty()) {
if (s[i] == q.front()) {
cnt++;
i++;
}
q.pop();
}
if (cnt == s.size())
return true ;
else
return false ;
}
int main()
{
string s1 = "gksrek" ;
string s2 = "geeksforgeeks" ;
if (issubsequence(s1, s2))
cout << "gksrek is subsequence of geeksforgeeks"
<< endl;
else
cout << "gksrek is not a subsequence of "
"geeksforgeeks"
<< endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static boolean isSubsequence(String s, String t) {
Queue<Character> q = new LinkedList<>();
int cnt = 0 ;
for ( int i = 0 ; i < t.length(); i++) {
q.add(t.charAt(i));
}
int i = 0 ;
while (!q.isEmpty() && i < s.length()) {
if (s.charAt(i) == q.peek()) {
cnt++;
i++;
}
q.poll();
}
return cnt == s.length();
}
public static void main(String[] args) {
String s1 = "gksrek" ;
String s2 = "geeksforgeeks" ;
if (isSubsequence(s1, s2))
System.out.println( "gksrek is a subsequence of geeksforgeeks" );
else
System.out.println( "gksrek is not a subsequence of geeksforgeeks" );
}
}
|
Python
from queue import Queue
def IsSubsequence(s, t):
q = Queue()
cnt = 0
for x in t:
q.put(x)
i = 0
while not q.empty() and i < len (s):
if s[i] = = q.queue[ 0 ]:
cnt + = 1
i + = 1
q.get()
return cnt = = len (s)
s1 = "gksrek"
s2 = "geeksforgeeks"
if IsSubsequence(s1, s2):
print ( "gksrek is a subsequence of geeksforgeeks" )
else :
print ( "gksrek is not a subsequence of geeksforgeeks" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static bool IsSubsequence( string s, string t)
{
Queue< char > q = new Queue< char >();
int cnt = 0;
for ( int x = 0; x < t.Length; x++)
{
q.Enqueue(t[x]);
}
int i = 0;
while (q.Count > 0 && i < s.Length)
{
if (s[i] == q.Peek())
{
cnt++;
i++;
}
q.Dequeue();
}
return cnt == s.Length;
}
public static void Main( string [] args)
{
string s1 = "gksrek" ;
string s2 = "geeksforgeeks" ;
if (IsSubsequence(s1, s2))
Console.WriteLine( "gksrek is a subsequence of geeksforgeeks" );
else
Console.WriteLine( "gksrek is not a subsequence of geeksforgeeks" );
}
}
|
Javascript
function isSubsequence(s, t) {
let q = [];
let cnt = 0;
for (let x = 0; x < t.length; x++) {
q.push(t[x]);
}
let i = 0;
while (q.length > 0 && i < s.length) {
if (s[i] === q[0]) {
cnt++;
i++;
}
q.shift();
}
return cnt === s.length;
}
const s1 = "gksrek" ;
const s2 = "geeksforgeeks" ;
if (isSubsequence(s1, s2))
console.log( "gksrek is a subsequence of geeksforgeeks" );
else
console.log( "gksrek is not a subsequence of geeksforgeeks" );
|
Outputgksrek is subsequence of geeksforgeeks
Time Complexity: O(n), as we are linearly traversing both the strings entirely.
Auxiliary Space: O(n),for extra space occupied by queue.