Count of ‘GFG’ Subsequences in the given string
Last Updated :
17 Aug, 2022
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++
#include <bits/stdc++.h>
using namespace std;
#define MAX 100
void countSubsequence( char s[], int n)
{
int cntG = 0, cntF = 0, result = 0, C=0;
for ( int i = 0; i < n; i++) {
switch (s[i]) {
case 'G' :
cntG++;
result+=C;
break ;
case 'F' :
cntF++;
C+=cntG;
break ;
default :
continue ;
}
}
cout << result << endl;
}
int main()
{
char s[] = "GFGFG" ;
int n = strlen (s);
countSubsequence(s, n);
return 0;
}
|
Java
public class GFG {
static int max = 100 ;
static void countSubsequence(String s, int n)
{
int cntG = 0 , cntF = 0 , result = 0 , C= 0 ;
for ( int i = 0 ; i < n; i++) {
switch (s.charAt(i)) {
case 'G' :
cntG++;
result+=C;
break ;
case 'F' :
cntF++;
C+=cntG;
break ;
default :
continue ;
}
}
System.out.println(result);
}
public static void main(String args[]) {
String s= "GFGFG" ;
int n = s.length();
countSubsequence(s, n);
}
}
|
Python3
MAX = 100
def countSubsequence(s, n):
cntG = 0
cntF = 0
result = 0
C = 0
for i in range (n):
if (s[i] = = 'G' ):
cntG + = 1
result + = C
continue
if (s[i] = = 'F' ):
cntF + = 1
C + = cntG
continue
else :
continue
print (result)
if __name__ = = '__main__' :
s = "GFGFG"
n = len (s)
countSubsequence(s, n)
|
C#
using System;
class GFG {
static void countSubsequence( string s,
int n)
{
int cntG = 0, cntF = 0, result = 0, C=0;
for ( int i = 0; i < n; i++) {
switch (s[i]) {
case 'G' :
cntG++;
result += C;
break ;
case 'F' :
cntF++;
C+=cntG;
break ;
default :
continue ;
}
}
Console.WriteLine(result);
}
public static void Main()
{
string s= "GFGFG" ;
int n = s.Length;
countSubsequence(s, n);
}
}
|
Javascript
<script>
var MAX = 100;
function countSubsequence( s, n)
{
var cntG = 0, cntF = 0, result = 0, C=0;
for ( var i = 0; i < n; i++) {
switch (s[i]) {
case 'G' :
cntG++;
result+=C;
break ;
case 'F' :
cntF++;
C+=cntG;
break ;
default :
continue ;
}
}
document.write( result );
}
var s = "GFGFG" ;
var n = (s.length);
countSubsequence(s, n);
</script>
|
Complexity Analysis:
- Time Complexity : O(n)
- Auxiliary Space: O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...