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)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count subsequences in first string which are anagrams of the second string
- Count all subsequences having product less than K
- Count all increasing subsequences
- Count Distinct Subsequences
- Count subsequences with same values of Bitwise AND, OR and XOR
- Count of subsequences of length 4 in form (x, x, x+1, x+1) | Set 2
- Count of subsequences in an array with sum less than or equal to X
- Construct a string that has exactly K subsequences from given string
- Print all subsequences of a string
- Count of all subsequences having adjacent elements with different parity
- Count of subsequences having maximum distinct elements
- Count of subsequences which consists exactly K prime numbers
- Find the count of subsequences where each element is divisible by K
- Count of possible subarrays and subsequences using given length of Array
- Count the number of subsequences of length k having equal LCM and HCF
- Number of subsequences in a string divisible by n
- Print all subsequences of a string using ArrayList
- Print all subsequences of a string in Python
- Count of subsequences whose product is a difference of square of two integers
- Number of subsequences in a given binary string divisible by 2
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.