Given a string of length n of capital letters. The task is to find the count of ‘GFG’ subsequence in the given string.
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:
Time Complexity : O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count subsequences in first string which are anagrams of the second string
- Construct a string that has exactly K subsequences from given string
- Check if a string can be obtained by appending subsequences of another string
- Count of possible subarrays and subsequences using given length of Array
- Maximize count of Decreasing Subsequences from the given Array
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9
- Given a number as a string, find the number of contiguous subsequences which recursively add up to 9 | Set 2
- Generating distinct subsequences of a given string in lexicographic order
- Lexicographically smallest permutation of a string with given subsequences
- Number of subsequences in a given binary string divisible by 2
- Convert given string to another by minimum replacements of subsequences by its smallest character
- Count all increasing subsequences
- Count minimum number of subsets (or subsequences) with consecutive numbers
- Count all subsequences having product less than K
- Count of subsequences having maximum distinct elements
- Find the count of subsequences where each element is divisible by K
- Count the number of subsequences of length k having equal LCM and HCF
- Count the number of contiguous increasing and decreasing subsequences in a sequence
- Count of subsequences in an array with sum less than or equal to X
- Count of subsequences whose product is a difference of square of two integers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.