Open In App

Count of Subsequences of given string X in between strings Y and Z

Given three strings, ‘X‘, ‘Y‘ and ‘Z‘, the task is to count the number of subsequences of ‘X‘ which is lexicographically greater than or equal to ‘Y‘ and lexicographically lesser than or equal to ‘Z‘. 

Examples: 



Input: X = “abc”, Y = “a”, Z = “bc”
Output: 6
Explanation: The subsequences of X which are greater than or equal to string  ‘Y’ and lesser than or equal to string ‘Z’ are 
{ “a”, “b”,  “ab”, “ac”, “bc”, “abc” }

Input: X = “ade”, Y = “a”, Z = “dc”
Output: 5
Explanation: The subsequences of X which are greater than or equal to string  ‘Y’ and lesser than or equal to string ‘Z’ are
{ “a”, “d”, “ad”, “ae”, “ade”}



 

Naive Approach: The simplest approach is to generate all subsequences of string ‘X‘ and check if it is greater than or equal to ‘Y‘ and lesser than or equal to ‘Z‘. 

Time Complexity: O(2N * N)
Auxiliary Space: O(N)

Efficient Approach: The above approach can also be optimized by using Dynamic Programming because it has overlapping subproblems and optimal substructure. The subproblems can be stored in dp[][][][] table using memoization where dp[idx1][idx2][bound1][bound2] stores the answer from the idx1th position of string ‘X‘ till the end and from the idx2th position of string ‘Y‘ and ‘Z‘ till the end, where bound1 is a boolean variable which tells if the subsequence constructed till idx1 is equal to the corresponding substring of ‘Y‘ till idx2 and bound2 is a boolean variable which tells if the subsequence constructed till idx1 is equal to the corresponding substring of ‘Z‘ till idx2

Follow the steps below to solve the problem: 

Illustration: 

X = “ac”

Y = “ab”

Z = “bc”

                                                                               count(0, 0, 1, 1)

                                                          / (Exclude)                                     \ Can be included (X[0] == Y[0], X[0] < Z[0])

                                                      /                                                            \ bound1 = 1, bound2 = 0 (as X[0]  < Z[0] )

                                   count(1, 0, 1, 1)                                               count(1, 1, 1, 0)

                            / (Exclude)   \ Cannot be included               / (Exclude)             \ Can be included (X[1] > Y[1], X[1] == Z[1])

                      /                          \  X[1] > Y[0]                             /                                   \ bound1 = 0 (as X[1] > Y[1])

                 /                                \ but X[1] > Z[0]                  /                                         \ bound2 = 0 (as it was previously also 0)

  Returns ‘0’   [“”]                 Returns ‘0’ [“c”]          Returns ‘0’ [“a”]                       Returns ‘1’  [“ac”]

 empty subsequence                                                      [bound1 = 1,                               [bound1 = 0]

    [idx2 == 0]                                                            but idx2 < Y.size()]             

Hence the final answer is 1, i.e., “ac”.

Below is the implementation of the above approach: 




// C++ program for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
int dp[100][100][2][2];
 
string X, Y, Z;
int XSize, YSize, ZSize;
 
// Function to find the count
// of subsequences of 'X' which
// is greater than or equal to 'Y'
// but lesser than or equal to 'Z'.
int countOfSubsequence(
    int idx1, int idx2,
    bool bound1, bool bound2)
{
 
    // If the string 'X'
    // is traversed completely.
    if (idx1 == XSize) {
 
        // If subsequence is empty, return 0.
        if (idx2 == 0)
            return 0;
 
        // If bound1 is false (current subsequence
        // is larger than 'Y') or
        // idx2 is greater than or
        // equal to Ysize, return 1.
        if (!bound1 or idx2 >= YSize)
            return 1;
 
        // Else return 0.
        return 0;
    }
 
    // If the state has already
    // been computed, return it.
    if (dp[idx1][idx2][bound1][bound2] != -1) {
        return dp[idx1][idx2][bound1][bound2];
    }
 
    // Exclude the current element
    // from the subsequence.
    int ans = countOfSubsequence(
        idx1 + 1, idx2,
        bound1, bound2);
 
    // Variable to check if current
    // character can be included
    // the subsequence by checking
    // the strings 'Y' and 'Z'.
    int isOk = 0;
 
    // Check for first string
    // If bound1 is false,
    // it means the current character
    // can be included in the
    // subsequence as the current
    // subsequence is already
    // greater than the string 'Y'.
    if (!bound1) {
        ++isOk;
    }
 
    // If idx2 >= Ysize,
    // the subsequence formed by placing
    // current character is of greater length
    // than string 'Y', hence can be placed.
    // If current character is greater than
    // or equal to the corresponding
    // character in string 'Y', it can be placed.
    else if (idx2 >= YSize or X[idx1] >= Y[idx2]) {
        ++isOk;
        bound1 &= (idx2 < YSize
                   and X[idx1] == Y[idx2]);
    }
 
    // Check for second string
    // If bound2 is false,
    // it means the current character
    // can be included in the subsequence
    // as the current subsequence is already
    // lesser than the string 'Z'.
    if (!bound2) {
        ++isOk;
    }
 
    // If current character is lesser than
    // or equal to the corresponding character
    // in string 'Z', it can be placed.
    else if (idx2 < ZSize
             and X[idx1] <= Z[idx2]) {
        ++isOk;
        bound2 &= (X[idx1] == Z[idx2]);
    }
 
    // If constraints are met by both string
    // 'Y' and 'Z', it is possible to include
    // the current character of
    // string 'X' in the subsequence.
    if (isOk == 2) {
 
        // Increase both idx1 and idx2 by 1.
        ans += countOfSubsequence(
            idx1 + 1, idx2 + 1,
            bound1, bound2);
    }
 
    // Return the answer.
    return dp[idx1][idx2][bound1][bound2] = ans;
}
 
// Utility function to find the count
// of subsequences of 'X' which is
// greater than or equal to 'Y'
// but lesser than or equal to 'Z'.
int UtilCountOfSubsequence()
{
 
    // Initialize the dp array with -1.
    memset(dp, -1, sizeof dp);
 
    // Calculate the size of strings
    //'X', 'Y', and 'Z'.
    XSize = X.size();
    YSize = Y.size();
    ZSize = Z.size();
 
    // Function call
    return countOfSubsequence(0, 0, 1, 1);
}
 
// Driver code
int main()
{
    // Input strings 'X', 'Y' and 'Z'.
    X = "abc";
    Y = "a";
    Z = "bc";
 
    // If string 'Y' is greater
    // than string 'Z', return 0.
    if (Y > Z) {
        cout << 0 << endl;
        return 0;
    }
 
    cout << UtilCountOfSubsequence()
         << endl;
}




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
 
  static int [][][][] dp = new int[100][100][2][2];
 
  static String X, Y, Z;
  static int XSize, YSize, ZSize;
 
  // Function to find the count
  // of subsequences of 'X' which
  // is greater than or equal to 'Y'
  // but lesser than or equal to 'Z'.
  static int countOfSubsequence(int idx1, int idx2,Boolean bound1, Boolean bound2)
  {
 
    // If the string 'X'
    // is traversed completely.
    if (idx1 == XSize) {
 
      // If subsequence is empty, return 0.
      if (idx2 == 0)
        return 0;
 
      // If bound1 is false (current subsequence
      // is larger than 'Y') or
      // idx2 is greater than or
      // equal to Ysize, return 1.
      if (!bound1 || idx2 >= YSize)
        return 1;
 
      // Else return 0.
      return 0;
    }
 
    // If the state has already
    // been computed, return it.
    if (dp[idx1][idx2][bound1?1:0][bound2?1:0] != -1) {
      return dp[idx1][idx2][bound1?1:0][bound2?1:0];
    }
 
    // Exclude the current element
    // from the subsequence.
    int ans = countOfSubsequence(idx1 + 1, idx2, bound1, bound2);
 
    // Variable to check if current
    // character can be included
    // the subsequence by checking
    // the strings 'Y' and 'Z'.
    int isOk = 0;
 
    // Check for first string
    // If bound1 is false,
    // it means the current character
    // can be included in the
    // subsequence as the current
    // subsequence is already
    // greater than the string 'Y'.
    if (bound1 == false) {
      ++isOk;
    }
 
    // If idx2 >= Ysize,
    // the subsequence formed by placing
    // current character is of greater length
    // than string 'Y', hence can be placed.
    // If current character is greater than
    // or equal to the corresponding
    // character in string 'Y', it can be placed.
    else if (idx2 >= YSize || (int)X.charAt(idx1) >= (int)Y.charAt(idx2)) {
      ++isOk;
      bound1 &= (idx2 < YSize && X.charAt(idx1) == Y.charAt(idx2));
    }
 
    // Check for second string
    // If bound2 is false,
    // it means the current character
    // can be included in the subsequence
    // as the current subsequence is already
    // lesser than the string 'Z'.
    if (!bound2) {
      ++isOk;
    }
 
    // If current character is lesser than
    // or equal to the corresponding character
    // in string 'Z', it can be placed.
    else if (idx2 < ZSize && (int)X.charAt(idx1) <= (int)Z.charAt(idx2)) {
      ++isOk;
      bound2 &= (X.charAt(idx1) == Z.charAt(idx2));
    }
 
    // If constraints are met by both string
    // 'Y' and 'Z', it is possible to include
    // the current character of
    // string 'X' in the subsequence.
    if (isOk == 2) {
 
      // Increase both idx1 and idx2 by 1.
      ans += countOfSubsequence(idx1 + 1, idx2 + 1, bound1, bound2);
    }
 
    // Return the answer.
    return dp[idx1][idx2][bound1?1:0][bound2?1:0] = ans;
  }
 
  // Utility function to find the count
  // of subsequences of 'X' which is
  // greater than or equal to 'Y'
  // but lesser than or equal to 'Z'.
  static int UtilCountOfSubsequence()
  {
 
    // Initialize the dp array with -1.
    for(int i=0;i<100;i++){
      for(int j=0;j<100;j++){
        for(int k=0;k<2;k++){
          for(int l=0;l<2;l++){
            dp[i][j][k][l] = -1;
          }
        }
      }
    }
 
    // Calculate the size of strings
    //'X', 'Y', and 'Z'.
    XSize = X.length();
    YSize = Y.length();
    ZSize = Z.length();
 
    // Function call
    return countOfSubsequence(0, 0, true , true);
  }
 
  // Driver code
  public static void main(String args[])
  {
    // Input strings 'X', 'Y' and 'Z'.
    X = "abc";
    Y = "a";
    Z = "bc";
 
    // If string 'Y' is greater
    // than string 'Z', return 0.
    if (Y.compareTo(Z) > 0) {
      System.out.println(0);
      return;
    }
 
    System.out.println(UtilCountOfSubsequence());
  }
}
 
  // This code is contributed by shinjanpatra




# Python3 code for the above approach
 
dp = [None] * 100
 
for i in range(len(dp)):
    dp[i] = [None] * 100
    for j in range(len(dp[i])):
        dp[i][j] = [None, None]
        for k in range(len(dp[i][j])):
            dp[i][j][k] = [-1, -1]
 
 
X, Y, Z = 0, 0, 0
XSize, YSize, ZSize = 0, 0, 0
 
# Function to find the count
# of subsequences of 'X' which
# is greater than or equal to 'Y'
# but lesser than or equal to 'Z'.
def countOfSubsequence(idx1, idx2, bound1, bound2):
    global X, Y, Z, XSize, YSize, ZSize, dp
     
    # If the string 'X'
    # is traversed completely.
    if (idx1 == XSize):
 
        # If subsequence is empty, return 0.
        if (idx2 == 0):
            return 0
 
        # If bound1 is false (current subsequence
        # is larger than 'Y') or
        # idx2 is greater than or
        # equal to Ysize, return 1.
        if (not bound1 or idx2 >= YSize):
            return 1
 
        # Else return 0.
        return 0
 
    # If the state has already
    # been computed, return it.
    if (dp[idx1][idx2][bound1][bound2] != -1):
        return dp[idx1][idx2][bound1][bound2]
 
    # Exclude the current element
    # from the subsequence.
    ans = countOfSubsequence(idx1 + 1, idx2, bound1,
                             bound2)
 
    # Variable to check if current
    # character can be included
    # the subsequence by checking
    # the strings 'Y' and 'Z'.
    isOk = 0
 
    # Check for first string
    # If bound1 is false,
    # it means the current character
    # can be included in the
    # subsequence as the current
    # subsequence is already
    # greater than the string 'Y'.
    if (not bound1):
        isOk += 1
 
    # If idx2 >= Ysize,
    # the subsequence formed by placing
    # current character is of greater length
    # than string 'Y', hence can be placed.
    # If current character is greater than
    # or equal to the corresponding
    # character in string 'Y', it can be placed.
    elif (idx2 >= YSize or X[idx1] >= Y[idx2]):
        isOk += 1
        bound1 &= (idx2 < YSize and X[idx1] == Y[idx2])
 
    # Check for second string
    # If bound2 is false,
    # it means the current character
    # can be included in the subsequence
    # as the current subsequence is already
    # lesser than the string 'Z'.
    if (not bound2):
        isOk += 1
 
    # If current character is lesser than
    # or equal to the corresponding character
    # in string 'Z', it can be placed.
    elif (idx2 < ZSize and X[idx1] <= Z[idx2]):
        isOk += 1
        bound2 &= (X[idx1] == Z[idx2])
 
    # If constraints are met by both string
    # 'Y' && 'Z', it is possible to include
    # the current character of
    # string 'X' in the subsequence.
    if (isOk == 2):
 
        # Increase both idx1 && idx2 by 1.
        ans += countOfSubsequence(idx1 + 1, idx2 + 1,
                                  bound1, bound2)
 
    # Return the answer.
    dp[idx1][idx2][bound1][bound2] = ans
    return ans
 
# Utility function to find the count
# of subsequences of 'X' which is
# greater than or equal to 'Y'
# but lesser than or equal to 'Z'.
def UtilCountOfSubsequence():
    global X, Y, Z, XSize, YSize, ZSize, dp
 
    # Calculate the size of strings
    # 'X', 'Y', and 'Z'.
    XSize = len(X)
    YSize = len(Y)
    ZSize = len(Z)
 
    # Function call
    return countOfSubsequence(0, 0, 1, 1)
 
# Driver code
 
# Input strings 'X', 'Y' and 'Z'.
X = "abc"
Y = "a"
Z = "bc"
 
# If string 'Y' is greater
# than string 'Z', return 0.
if (Y > Z):
    print(0)
 
print(UtilCountOfSubsequence())
 
# This code is contributed by phasing17




// C# program to implement above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    public static int[, , ,] dp = new int[100, 100, 2, 2];
 
    public static String X = "", Y = "", Z = "";
    public static int XSize, YSize, ZSize;
 
    // Return 1 if bool is true
    // else false
    public static int boolToInt(bool input){
        if(input) return 1;
        return 0;
    }
 
    // Function to find the count
    // of subsequences of 'X' which
    // is greater than or equal to 'Y'
    // but lesser than or equal to 'Z'.
    public static int countOfSubsequence(int idx1, int idx2, bool bound1, bool bound2)
    {
 
        // If the string 'X'
        // is traversed completely.
        if (idx1 == XSize) {
 
            // If subsequence is empty, return 0.
            if (idx2 == 0)
                return 0;
 
            // If bound1 is false (current subsequence
            // is larger than 'Y') or
            // idx2 is greater than or
            // equal to Ysize, return 1.
            if (!bound1 || idx2 >= YSize)
                return 1;
 
            // Else return 0.
            return 0;
        }
 
        // If the state has already
        // been computed, return it.
        if (dp[idx1, idx2, boolToInt(bound1), boolToInt(bound2)] != -1) {
            return dp[idx1, idx2, boolToInt(bound1), boolToInt(bound2)];
        }
 
        // Exclude the current element
        // from the subsequence.
        int ans = countOfSubsequence(idx1 + 1, idx2, bound1, bound2);
 
        // Variable to check if current
        // character can be included
        // the subsequence by checking
        // the strings 'Y' and 'Z'.
        int isOk = 0;
 
        // Check for first string
        // If bound1 is false,
        // it means the current character
        // can be included in the
        // subsequence as the current
        // subsequence is already
        // greater than the string 'Y'.
        if (!bound1) {
            ++isOk;
        }
 
        // If idx2 >= Ysize,
        // the subsequence formed by placing
        // current character is of greater length
        // than string 'Y', hence can be placed.
        // If current character is greater than
        // or equal to the corresponding
        // character in string 'Y', it can be placed.
        else if (idx2 >= YSize || X[idx1] >= Y[idx2]){
            ++isOk;
            bound1 &= (idx2 < YSize && X[idx1] == Y[idx2]);
        }
 
        // Check for second string
        // If bound2 is false,
        // it means the current character
        // can be included in the subsequence
        // as the current subsequence is already
        // lesser than the string 'Z'.
        if (!bound2) {
            ++isOk;
        }
 
        // If current character is lesser than
        // or equal to the corresponding character
        // in string 'Z', it can be placed.
        else if (idx2 < ZSize && X[idx1] <= Z[idx2]) {
            ++isOk;
            bound2 &= (X[idx1] == Z[idx2]);
        }
 
        // If constraints are met by both string
        // 'Y' and 'Z', it is possible to include
        // the current character of
        // string 'X' in the subsequence.
        if (isOk == 2) {
 
            // Increase both idx1 and idx2 by 1.
            ans += countOfSubsequence(idx1 + 1, idx2 + 1, bound1, bound2);
        }
 
        // Return the answer.
        return dp[idx1, idx2, boolToInt(bound1), boolToInt(bound2)] = ans;
    }
 
    // Utility function to find the count
    // of subsequences of 'X' which is
    // greater than or equal to 'Y'
    // but lesser than or equal to 'Z'.
    public static int UtilCountOfSubsequence()
    {
 
        // Initialize the dp array with -1.
        for(int i=0 ; i<100 ; i++){
            for(int j=0 ; j<100 ; j++){
                for(int k=0 ; k<2 ; k++){
                    for(int l=0 ; l<2 ; l++){
                        dp[i, j, k, l] = -1;
                    }
                }
            }
        }
 
        // Calculate the size of strings
        //'X', 'Y', and 'Z'.
        XSize = X.Length;
        YSize = Y.Length;
        ZSize = Z.Length;
 
        // Function call
        return countOfSubsequence(0, 0, true, true);
    }
 
 
    // Driver Code
    public static void Main(string[] args){
         
        // Input strings 'X', 'Y' and 'Z'.
        X = "abc";
        Y = "a";
        Z = "bc";
 
        // If string 'Y' is greater
        // than string 'Z', return 0.
        if (Y.CompareTo(Z) > 0) {
            Console.Write(0);
            return;
        }
 
        Console.Write(UtilCountOfSubsequence());
    }
}
 
// This code is contributed by subhamgoyal2014.




<script>
      // JavaScript code for the above approach
 
 
      let dp = new Array(100);
 
 
      for (let i = 0; i < dp.length; i++) {
 
          dp[i] = new Array(100)
 
          for (let j = 0; j < dp[i].length; j++) {
              dp[i][j] = new Array(2)
 
              for (let k = 0; k < dp[i][j].length; k++) {
                  dp[i][j][k] = new Array(2).fill(-1)
              }
          }
      }
 
      let X, Y, Z;
      let XSize, YSize, ZSize;
 
      // Function to find the count
      // of subsequences of 'X' which
      // is greater than or equal to 'Y'
      // but lesser than or equal to 'Z'.
      function countOfSubsequence(
          idx1, idx2,
          bound1, bound2) {
 
          // If the string 'X'
          // is traversed completely.
          if (idx1 == XSize) {
 
              // If subsequence is empty, return 0.
              if (idx2 == 0)
                  return 0;
 
              // If bound1 is false (current subsequence
              // is larger than 'Y') or
              // idx2 is greater than or
              // equal to Ysize, return 1.
              if (!bound1 || idx2 >= YSize)
                  return 1;
 
              // Else return 0.
              return 0;
          }
 
          // If the state has already
          // been computed, return it.
          if (dp[idx1][idx2][bound1][bound2] != -1) {
              return dp[idx1][idx2][bound1][bound2];
          }
 
          // Exclude the current element
          // from the subsequence.
          let ans = countOfSubsequence(
              idx1 + 1, idx2,
              bound1, bound2);
 
          // Variable to check if current
          // character can be included
          // the subsequence by checking
          // the strings 'Y' and 'Z'.
          let isOk = 0;
 
          // Check for first string
          // If bound1 is false,
          // it means the current character
          // can be included in the
          // subsequence as the current
          // subsequence is already
          // greater than the string 'Y'.
          if (!bound1) {
              ++isOk;
          }
 
          // If idx2 >= Ysize,
          // the subsequence formed by placing
          // current character is of greater length
          // than string 'Y', hence can be placed.
          // If current character is greater than
          // or equal to the corresponding
          // character in string 'Y', it can be placed.
          else if (idx2 >= YSize || X[idx1] >= Y[idx2]) {
              ++isOk;
              bound1 &= (idx2 < YSize
                  && X[idx1] == Y[idx2]);
          }
 
          // Check for second string
          // If bound2 is false,
          // it means the current character
          // can be included in the subsequence
          // as the current subsequence is already
          // lesser than the string 'Z'.
          if (!bound2) {
              ++isOk;
          }
 
          // If current character is lesser than
          // or equal to the corresponding character
          // in string 'Z', it can be placed.
          else if (idx2 < ZSize
              && X[idx1] <= Z[idx2]) {
              ++isOk;
              bound2 &= (X[idx1] == Z[idx2]);
          }
 
          // If constraints are met by both string
          // 'Y' && 'Z', it is possible to include
          // the current character of
          // string 'X' in the subsequence.
          if (isOk == 2) {
 
              // Increase both idx1 && idx2 by 1.
              ans += countOfSubsequence(
                  idx1 + 1, idx2 + 1,
                  bound1, bound2);
          }
 
          // Return the answer.
          return dp[idx1][idx2][bound1][bound2] = ans;
      }
 
      // Utility function to find the count
      // of subsequences of 'X' which is
      // greater than or equal to 'Y'
      // but lesser than or equal to 'Z'.
      function UtilCountOfSubsequence() {
 
 
          // Calculate the size of strings
          //'X', 'Y', and 'Z'.
          XSize = X.length;
          YSize = Y.length;
          ZSize = Z.length;
 
          // Function call
          return countOfSubsequence(0, 0, 1, 1);
      }
 
      // Driver code
 
      // Input strings 'X', 'Y' and 'Z'.
      X = "abc";
      Y = "a";
      Z = "bc";
 
      // If string 'Y' is greater
      // than string 'Z', return 0.
      if (Y > Z) {
          document.write(0 + '<br>')
      }
 
      document.write(UtilCountOfSubsequence()
          + '<br>')
 
 
 // This code is contributed by Potta Lokesh
 
  </script>

Output
6

Time Complexity: O(N2 * 2 * 2) 
Auxiliary Space: O(N2 * 2 * 2)


Article Tags :