Count subsequence of length three in a given string - GeeksforGeeks

04 May, 2021
Given a string of length n and a subsequence of length 3. Find the total number of occurrences of the subsequence in this string.
Examples : 
Input : string = "GFGFGYSYIOIWIN", 
        subsequence = "GFG"
Output : 4
Explanation : There are 4 such subsequences as shown:
              GFGFGYSYIOIWIN
              GFGFGYSYIOIWIN
              GFGFGYSYIOIWIN
              GFGFGYSYIOIWIN

Input : string = "GFGGGZZYNOIWIN", 
        subsequence = "GFG"
Output : 3
Brute Force Approach: The simplest way to solve this problem is to run three loops for the tree characters of the given subsequences. That starts a loop to find the first character of the subsequence in the string, once this character is found start a loop after this index to find the second character, once this character is found start a loop after this index to find the third character. Maintain a variable to store the number of occurrences of third character, i.e. number of occurrences of the subsequence.
Below is the implementation of above approach:  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of occurrences of// a subsequence of length 3#include<iostream>using namespace std; // Function to find number of occurrences of// a subsequence of length three in a stringint findOccurrences(string str, string substr){       // variable to store no of occurrences    int counter = 0;     // loop to find first character    for (int i=0;i<str.length();i++)    {        if (str[i]==substr[0])        {               // loop to find 2nd character            for (int j=i+1;j<str.length();j++)            {                if (str[j]==substr[1])                {                       // loop to find 3rd character                    for (int k = j+1; k<str.length(); k++)                    {                           // increment count if subsequence                        // is found                        if (str[k]==substr[2])                            counter++;                    }                }            }        }    }     return counter;} // Driver codeint main(){    string str = "GFGFGYSYIOIWIN";    string substr = "GFG";    cout << findOccurrences(str, substr);       return 0;}
// Java program to find number of occurrences of// a subsequence of length 3import java.util.*;import java.lang.*; public class GfG{         // Function to find number of occurrences of    // a subsequence of length three in a string    public static int findOccurrences(String str1, String substr1)    {        // variable to store no of occurrences        int counter = 0;                 char[] str = str1.toCharArray();        char[] substr = substr1.toCharArray();                 // loop to find first character        for (int i=0; i < str1.length(); i++)        {            if (str[i] == substr[0])            {                // loop to find 2nd character                for (int j = i+1; j < str1.length(); j++)                {                    if (str[j] == substr[1])                    {                        // loop to find 3rd character                        for (int k = j+1; k < str1.length(); k++)                        {                            // increment count if subsequence                            // is found                            if (str[k] == substr[2])                                counter++;                        }                    }                }            }        }         return counter;    }         // Driver function    public static void main(String argc[]){        String str = "GFGFGYSYIOIWIN";        String substr = "GFG";         System.out.println(findOccurrences(str, substr));    }     }/* This code is contributed by Sagar Shukla */
# Python program to find# number of occurrences# of a subsequence of# length 3 # Function to find number# of occurrences of a# subsequence of length# three in a stringdef findOccurrences(str, substr) :     # variable to store    # no of occurrences    counter = 0     # loop to find    # first character    for i in range(0, len(str)) :             if (str[i] == substr[0]) :                     # loop to find            # 2nd character            for j in range(i + 1,                           len(str)) :                             if (str[j] == substr[1]) :                                     # loop to find                    # 3rd character                    for k in range(j + 1,                                   len(str)) :                                             # increment count if                        # subsequence is found                        if (str[k] == substr[2]) :                            counter = counter + 1     return counter # Driver Codestr = "GFGFGYSYIOIWIN"substr = "GFG"print (findOccurrences(str, substr)) # This code is contributed by# Manish Shaw(manishshaw1)
// C# program to find number of occurrences of// a subsequence of length 3using System; public class GfG {         // Function to find number of occurrences of    // a subsequence of length three in a string    public static int findOccurrences(string str1,                                   string substr1)    {                 // variable to store no of occurrences        int counter = 0;                 //char[] str = str1.toCharArray();        //char[] substr = substr1.toCharArray();                 // loop to find first character        for (int i=0; i < str1.Length; i++)        {            if (str1[i] == substr1[0])            {                                 // loop to find 2nd character                for (int j = i+1; j < str1.Length; j++)                {                    if (str1[j] == substr1[1])                    {                                                 // loop to find 3rd character                        for (int k = j+1; k < str1.Length; k++)                        {                                                         // increment count if subsequence                            // is found                            if (str1[k] == substr1[2])                                counter++;                        }                    }                }            }        }         return counter;    }         // Driver function    public static void Main()    {        string str1 = "GFGFGYSYIOIWIN";        string substr1 = "GFG";         Console.WriteLine(findOccurrences(str1, substr1));    }} /* This code is contributed by vt_m */
<?php// PHP program to find number// of occurrences of a// subsequence of length 3 // Function to find number of// occurrences of a subsequence// of length three in a stringfunction findOccurrences($str, $substr){    // variable to store    // no of occurrences    $counter = 0;     // loop to find first character    for ($i = 0;$i < strlen($str); $i++)    {        if ($str[$i] == $substr[0])        {            // loop to find 2nd character            for ($j = $i + 1; $j < strlen($str); $j++)            {                if ($str[$j] == $substr[1])                {                    // loop to find 3rd character                    for ($k = $j + 1; $k < strlen($str); $k++)                    {                        // increment count if                        // subsequence is found                        if ($str[$k] == $substr[2])                            $counter++;                    }                }            }        }    }     return $counter;} // Driver Code$str = "GFGFGYSYIOIWIN";$substr = "GFG";echo findOccurrences($str, $substr); // This code is contributed by aj_36?>
<script> // Javascript program to find number// of occurrences of a subsequence of length 3 // Function to find number of occurrences of// a subsequence of length three in a stringfunction findOccurrences(str1, substr1){         // Variable to store no of occurrences    let counter = 0;           //char[] str = str1.toCharArray();    //char[] substr = substr1.toCharArray();           // Loop to find first character    for(let i = 0; i < str1.length; i++)    {        if (str1[i] == substr1[0])        {                         // Loop to find 2nd character            for(let j = i + 1; j < str1.length; j++)            {                if (str1[j] == substr1[1])                {                                           // Loop to find 3rd character                    for (let k = j + 1; k < str1.length; k++)                    {                                                   // Increment count if subsequence                        // is found                        if (str1[k] == substr1[2])                            counter++;                    }                }            }        }    }    return counter;} // Driver codelet str1 = "GFGFGYSYIOIWIN";let substr1 = "GFG"; document.write(findOccurrences(str1, substr1)); // This code is contributed by suresh07  </script>
Output : 
4
Time Complexity: O(n^3) Auxiliary Space: O(1)
Efficient Approach: The efficient method to solve this problem is to use the concept of pre-calculation. The idea is for every occurrence of the middle character of subsequence in the string, pre-compute two values. That is, number of occurrences of first character before it and number of occurrences of third character after it and multiply these two values to generate total occurrences for each occurrence of middle character.
Below is the implementation of this idea:  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of occurrences of// a subsequence of length 3#include<iostream>using namespace std; // Function to find number of occurrences of// a subsequence of length three in a stringint findOccurrences(string str, string substr){       // calculate length of string    int n = str.length();     // auxiliary array to store occurrences of    // first character    int preLeft[n] = {0};     // auxiliary array to store occurrences of    // third character    int preRight[n] = {0};     if (str[0]==substr[0])        preLeft[0]++;     // calculate occurrences of first character    // upto ith index from left    for (int i=1;i<n;i++)    {        if (str[i]==substr[0])                   preLeft[i] = preLeft[i-1] + 1;               else            preLeft[i] = preLeft[i-1];           }     if (str[n-1]==substr[2])        preRight[n-1]++;     // calculate occurrences of third character    // upto ith index from right    for(int i=n-2;i>=0;i--)    {        if (str[i]==substr[2])                   preRight[i] = preRight[i+1] + 1;               else                   preRight[i] = preRight[i+1];           }     // variable to store total number of occurrences    int counter = 0;     // loop to find the occurrences of middle element    for (int i=1; i<n-1;i++)    {           // if middle character of subsequence is found        // in the string        if (str[i]==str[1])        {               // multiply the total occurrences of first            // character before middle character with            // the total occurrences of third character            // after middle character            int total = preLeft[i-1]*preRight[i+1];            counter += total;        }    }     return counter;} // Driver codeint main(){    string str = "GFGFGYSYIOIWIN";    string substr = "GFG";    cout << findOccurrences(str,substr);    return 0;}
// Java program to find number of occurrences of// a subsequence of length 3import java.util.*;import java.lang.*; public class GfG{         // Function to find number of occurrences of    // a subsequence of length three in a string    public static int findOccurrences(String str1, String substr1)    {        // calculate length of string        int n = str1.length();                 char[] str = str1.toCharArray();        char[] substr = substr1.toCharArray();                 // auxiliary array to store occurrences of        // first character        int[] preLeft = new int[n];         // auxiliary array to store occurrences of        // third character        int[] preRight = new int[n];         if (str[0] == substr[0])            preLeft[0]++;         // calculate occurrences of first character        // upto ith index from left        for (int i = 1; i < n; i++)        {            if (str[i] == substr[0])                    preLeft[i] = preLeft[i-1] + 1;                else                preLeft[i] = preLeft[i-1];            }         if (str[n-1] == substr[2])            preRight[n-1]++;         // calculate occurrences of third character        // upto ith index from right        for(int i = n-2; i >= 0; i--)        {            if (str[i] == substr[2])                    preRight[i] = preRight[i+1] + 1;                else                   preRight[i] = preRight[i+1];            }         // variable to store total number of occurrences        int counter = 0;         // loop to find the occurrences of middle element        for (int i = 1; i < n-1; i++)        {            // if middle character of subsequence is found            // in the string            if (str[i] == str[1])            {                // multiply the total occurrences of first                // character before middle character with                // the total occurrences of third character                // after middle character                int total = preLeft[i-1] * preRight[i+1];                counter += total;            }        }         return counter;    }         // Driver function    public static void main(String argc[]){        String str = "GFGFGYSYIOIWIN";        String substr = "GFG";                 System.out.println(findOccurrences(str, substr));    }         /* This code is contributed by Sagar Shukla */}
# Python 3 program to find number of# occurrences of a subsequence of length 3 # Function to find number of occurrences of# a subsequence of length three in a stringdef findOccurrences(str1, substr):         # calculate length of string    n = len(str1)     # auxiliary array to store occurrences of    # first character    preLeft = [0 for i in range(n)]     # auxiliary array to store occurrences of    # third character    preRight = [0 for i in range(n)]     if (str1[0] == substr[0]):        preLeft[0] += 1     # calculate occurrences of first character    # upto ith index from left    for i in range(1, n):        if (str1[i] == substr[0]):            preLeft[i] = preLeft[i - 1] + 1           else:            preLeft[i] = preLeft[i - 1]         if (str1[n - 1] == substr[2]):        preRight[n - 1] += 1     # calculate occurrences of third character    # upto ith index from right    i = n - 2    while(i >= 0):        if (str1[i] == substr[2]):            preRight[i] = preRight[i + 1] + 1           else:                preRight[i] = preRight[i + 1]         i -= 1     # variable to store    # total number of occurrences    counter = 0     # loop to find the occurrences    # of middle element    for i in range(1, n - 1):                 # if middle character of subsequence        # is found in the string        if (str1[i] == str1[1]):                         # multiply the total occurrences of first            # character before middle character with            # the total occurrences of third character            # after middle character            total = preLeft[i - 1] * preRight[i + 1]            counter += total     return counter # Driver codeif __name__ == '__main__':    str1 = "GFGFGYSYIOIWIN"    substr = "GFG"    print(findOccurrences(str1, substr))     # This code is contributed by# Surendra_Gangwar
// C# program to find number of occurrences of// a subsequence of length 3using System; public class GfG {         // Function to find number of occurrences of    // a subsequence of length three in a string    public static int findOccurrences(string str1,                                   string substr1)    {                 // calculate length of string        int n = str1.Length;                 // char[] str = str1.toCharArray();        // char[] substr = substr1.toCharArray();                 // auxiliary array to store occurrences of        // first character        int[] preLeft = new int[n];         // auxiliary array to store occurrences of        // third character        int[] preRight = new int[n];         if (str1[0] == substr1[0])            preLeft[0]++;         // calculate occurrences of first character        // upto ith index from left        for (int i = 1; i < n; i++)        {            if (str1[i] == substr1[0])                preLeft[i] = preLeft[i-1] + 1;            else                preLeft[i] = preLeft[i-1];        }         if (str1[n-1] == substr1[2])            preRight[n-1]++;         // calculate occurrences of third character        // upto ith index from right        for(int i = n-2; i >= 0; i--)        {            if (str1[i] == substr1[2])                preRight[i] = preRight[i+1] + 1;                else                preRight[i] = preRight[i+1];            }         // variable to store total number of occurrences        int counter = 0;         // loop to find the occurrences of middle element        for (int i = 1; i < n-1; i++)        {                         // if middle character of subsequence is found            // in the string            if (str1[i] == str1[1])            {                                 // multiply the total occurrences of first                // character before middle character with                // the total occurrences of third character                // after middle character                int total = preLeft[i-1] * preRight[i+1];                counter += total;            }        }         return counter;    }         // Driver function    public static void Main()    {        string str1 = "GFGFGYSYIOIWIN";        string substr1 = "GFG";                 Console.WriteLine(findOccurrences(str1, substr1));    }} /* This code is contributed by Vt_m */
<?php// PHP program to find number// of occurrences of a// subsequence of length 3 // Function to find number// of occurrences of a// subsequence of length// three in a stringfunction findOccurrences($str,                         $substr){    // calculate length of string    $n = strlen($str);     // auxiliary array to store    // occurrences of first character    $preLeft = array(0);     // auxiliary array to store    // occurrences of third character    $preRight = array(0);     if ($str[0] == $substr[0])        $preLeft[0]++;     // calculate occurrences    // of first character    // upto ith index from left    for ($i = 1; $i < $n; $i++)    {        if ($str[$i] == $substr[0])            $preLeft[$i] = $preLeft[$i - 1] + 1;        else            $preLeft[$i] = $preLeft[$i - 1];    }     if ($str[$n - 1] == $substr[2])        $preRight[$n - 1]++;     // calculate occurrences    // of third character    // upto ith index from right    for($i = $n - 2; $i >= 0; $i--)    {        if ($str[$i] == $substr[2])            $preRight[$i] = ($preRight[$i + 1] + 1);        else            $preRight[$i] = $preRight[$i + 1];        }     // variable to store total    // number of occurrences    $counter = 0;     // loop to find the occurrences    // of middle element    for ($i = 1; $i < $n - 1; $i++)    {        // if middle character of        // subsequence is found        // in the string        if ($str[$i] == $str[1])        {            // multiply the total occurrences            // of first character before            // middle character with the            // total occurrences of third            // character after middle character            $total = $preLeft[$i - 1] *                     $preRight[$i + 1];            $counter += $total;        }    }     return $counter;} // Driver Code$str = "GFGFGYSYIOIWIN";$substr = "GFG";echo findOccurrences($str, $substr); // This code is contributed by aj_36?>
<script>     // Javascript program to find    // number of occurrences    // of a subsequence of length 3         // Function to find number of occurrences of    // a subsequence of length three in a string    function findOccurrences(str, substr)    {                  // calculate length of string        let n = str.length;                  // char[] str = str.toCharArray();        // char[] substr = substr.toCharArray();                  // auxiliary array to store occurrences of        // first character        let preLeft = new Array(n);        preLeft.fill(0);          // auxiliary array to store occurrences of        // third character        let preRight = new Array(n);        preRight.fill(0);          if (str[0] == substr[0])            preLeft[0]++;          // calculate occurrences of first character        // upto ith index from left        for (let i = 1; i < n; i++)        {            if (str[i] == substr[0])                preLeft[i] = preLeft[i-1] + 1;            else                preLeft[i] = preLeft[i-1];        }          if (str[n-1] == substr[2])            preRight[n-1]++;          // calculate occurrences of third character        // upto ith index from right        for(let i = n-2; i >= 0; i--)        {            if (str[i] == substr[2])                preRight[i] = preRight[i+1] + 1;               else                preRight[i] = preRight[i+1];           }          // variable to store total        // number of occurrences        let counter = 0;          // loop to find the occurrences        // of middle element        for (let i = 1; i < n-1; i++)        {                          // if middle character of subsequence            // is found            // in the string            if (str[i] == str[1])            {                                  // multiply the total                // occurrences of first                // character before middle                // character with                // the total occurrences                // of third character                // after middle character                let total = preLeft[i-1] * preRight[i+1];                counter += total;            }        }          return counter;    }         let str = "GFGFGYSYIOIWIN";    let substr = "GFG";     document.write(findOccurrences(str, substr));     </script>
Output :  
4
Time Complexity: O(n) Auxiliary Space: O(n) 
jit_t
manishshaw1
SURENDRA_GANGWAR
nidhi_biet
suresh07
divyeshrabadiya07
prefix-sum
subsequence
Strings
prefix-sum
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Naive algorithm for Pattern Searching
Vigenère Cipher
Hill Cipher
Count words in a given string
How to Append a Character to a String in C
Convert character array to string in C++
sprintf() in C
Program to count occurrence of a given character in a string
Converting Roman Numerals to Decimal lying between 1 to 3999