Count of 'GFG' Subsequences in the given string - GeeksforGeeks

05 May, 2021
Given a string of length n of capital letters. The task is to find the count of ‘GFG’ subsequence in the given string.Examples:  
Input : str[] = "GFGFG"
Output : 4
GFGFG, GFGFG, GFGFG, GFGFG

Input : str[] = "ABCFGFPG"
Output : 1
 
To find the number of “GFG” subsequences in the given string, observe for each ‘F’ if we know number of ‘G’ before and after it. Then the number of “GFG” subsequence for that ‘F’ is equal to product of number of ‘G’ before and after that ‘F’. So, the idea is to maintain an array, arr[], where arr[i] store number of ‘G’ before index i, if ith character of the string is ‘F’ and number of ‘F’ before index i, if the ith character is ‘G’. Also, we will calculate and store the number of “GFG” subsequence in result whenever we encounter ‘G’.Below is the implementation of this approach:  
C++
Java
Python3
C#
Javascript
// CPP Program to find the "GFG" subsequence in// the given string#include <bits/stdc++.h>using namespace std;#define MAX 100 // Print the count of "GFG" subsequence in the stringvoid countSubsequence(char s[], int n){    int cntG = 0, cntF = 0, result = 0, C=0;     // Traversing the given string    for (int i = 0; i < n; i++) {        switch (s[i]) {         // If the character is 'G', increment        // the count of 'G', increase the result        // and update the array.        case 'G':            cntG++;            result+=C;            break;         // If the character is 'F', increment        // the count of 'F' and update the array.        case 'F':            cntF++;            C+=cntG;            break;         // Ignore other character.        default:            continue;        }    }     cout << result << endl;} // Driven Programint main(){    char s[] = "GFGFG";    int n = strlen(s);    countSubsequence(s, n);    return 0;}
// Java Program to find the "GFG" subsequence// in the given string public class GFG {     static int max = 100;             // Print the count of "GFG" subsequence    // in the string    static void countSubsequence(String s, int n)    {        int cntG = 0, cntF = 0, result = 0, C=0;             // Traversing the given string        for (int i = 0; i < n; i++) {            switch (s.charAt(i)) {                 // If the character is 'G',            // increment the count of 'G',            // increase the result and            // update the array.            case 'G':                cntG++;                result+=C;                break;                 // If the character is 'F',            // increment the count of 'F'            // and update the array.            case 'F':                cntF++;                C+=cntG;                break;                 // Ignore other character.            default:                continue;            }        }             System.out.println(result);    }         // Driver code       public static void main(String args[]) {        String s= "GFGFG";        int n = s.length();        countSubsequence(s, n);    }} // This code is contributed by Sam007
# Python 3 Program to find the "GFG"# subsequence in the given stringMAX = 100 # Print the count of "GFG" subsequence# in the stringdef countSubsequence(s, n):    cntG = 0    cntF = 0    result = 0    C=0      # Traversing the given string    for i in range(n):        if (s[i] == 'G'):                         # If the character is 'G', increment            # the count of 'G', increase the result            # and update the array.            cntG += 1            result += C            continue         # If the character is 'F', increment        # the count of 'F' and update the array.        if (s[i] == 'F'):            cntF += 1            C += cntG            continue         # Ignore other character.        else:            continue         print(result) # Driver Codeif __name__ == '__main__':    s = "GFGFG"    n = len(s)    countSubsequence(s, n)     # This code is contributed by# Sanjit_Prasad
// C# Program to find the "GFG" subsequence// in the given stringusing System; class GFG {             // Print the count of "GFG" subsequence    // in the string    static void countSubsequence(string s,                                     int n)    {        int cntG = 0, cntF = 0, result = 0, C=0;             // Traversing the given string        for (int i = 0; i < n; i++) {            switch (s[i]) {                 // If the character is 'G',            // increment the count of 'G',            // increase the result and            // update the array.            case 'G':                cntG++;                result += C;                break;                 // If the character is 'F',            // increment the count of 'F'            // and update the array.            case 'F':                cntF++;                C+=cntG;                break;                 // Ignore other character.            default:                continue;            }        }             Console.WriteLine(result);    }         // Driver code    public static void Main()    {        string s= "GFGFG";        int n = s.Length;        countSubsequence(s, n);    }} // This code is contributed by Sam007.
<script>  // Javascript Program to find the "GFG" subsequence in// the given stringvar MAX = 100; // Print the count of "GFG" subsequence in the stringfunction countSubsequence( s, n){    var cntG = 0, cntF = 0, result = 0, C=0;     // Traversing the given string    for (var i = 0; i < n; i++) {        switch (s[i]) {         // If the character is 'G', increment        // the count of 'G', increase the result        // and update the array.        case 'G':            cntG++;            result+=C;            break;         // If the character is 'F', increment        // the count of 'F' and update the array.        case 'F':            cntF++;            C+=cntG;            break;         // Ignore other character.        default:            continue;        }    }     document.write( result );} // Driven Programvar s = "GFGFG";var n = (s.length);countSubsequence(s, n); // This code is contributed by itsok.</script>
4
 
Time Complexity : O(n)  
YouTubeGeeksforGeeks507K subscribersCount of ‘GFG’ Subsequences in the given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:17•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=YdIncySuYXo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
Sam007
Sanjit_Prasad
kreedo
itsok
frequency-counting
subsequence
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
Reverse words in a given string
How to split a string in C/C++, Python and Java?