Subarray/Substring vs Subsequence and Programs to Generate them
1. visit: https://www.geeksforgeeks.org/subarraysubstring-vs-subsequence-and-programs-to-generate-them/
2. Print all subsequences of a string in Python:
a b c ab ac bc abc
3. Count of ‘GFG’ Subsequences in the given string
Examples:
Input : str[] = "GFGFG" Output : 4 GFGFG, GFGFG, GFGFG, GFGFG Input : str[] = "ABCFGFPG" Output : 1
4
Time Complexity : O(n)
4.Count Distinct Subsequences
Given a string, find the count of distinct subsequences of it.
Examples:
Input : str = "gfg" Output : 7 The seven distinct subsequences are "", "g", "f", "gf", "fg", "gg" and "gfg" Input : str = "ggg" Output : 4 The four distinct subsequences are "", "g", "gg" and "ggg"
Output:
7
Time Complexity : O(n)
Auxiliary Space : O(n)
5.Count all subsequences having product less than K
Given a non negative array, find the number of subsequences having product smaller than K.
Examples:
Input : [1, 2, 3, 4]
k = 10
Output :11
The subsequences are {1}, {2}, {3}, {4},
{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4},
{1, 2, 3}, {1, 2, 4}
Input : [4, 8, 7, 2]
k = 50
Output : 9
Output:
11
6. Number of subsequences with positive product
Given an array arr[] of N integers, the task is to find the count of all the subsequences of the array that have positive product.
Example:
Input: arr[] = {2, -3, -1}
Output: 3
{2}, {-3, -1} and {2, -3, -1} are the only possible subsequences.Input: arr[] = {2, 3, -1, 4, 5}
Output: 15Efficient approach:
- Count the number of positive and negative elements in the array.
- Any number of positive elements can be chosen for the subsequence to maintain the positive product. The number of different combinations of subsequences with all the positive elements will be pow(2, count of positive elements).
- An even number of negative elements can be chosen for the subsequence to maintain the positive product. The number of different combinations of subsequences with an even number of negative elements will be pow(2, count of negative elements – 1).
- After that, remove 1 from the results for the empty subsequence.
Below is the implementation of the above approach:Output:7Time Complexity: O(n)
Comments
Post a Comment