![]() |
VOOZH | about |
Given a string, count number of subsequences of the form aibjck, i.e., it consists of i ’a’ characters, followed by j ’b’ characters, followed by k ’c’ characters where i >= 1, j >=1 and k >= 1.
Note: Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different.
Expected Time Complexity: O(n)
Examples:
Input : abbc
Output : 3
Subsequences are abc, abc and abbc
Input : abcabc
Output : 7
Subsequences are abc, abc, abbc, aabc
abcc, abc and abc
Approach:
We traverse given string. For every character encounter, we do the following:
- Initialize counts of different subsequences caused by different combination of 'a'. Let this count be aCount.
- Initialize counts of different subsequences caused by different combination of 'b'. Let this count be bCount.
- Initialize counts of different subsequences caused by different combination of 'c'. Let this count be cCount.
- Traverse all characters of given string. Do following for current character s[i]
- If current character is 'a', then there are following possibilities :O(1).
- Current character begins a new subsequence.
- Current character is part of aCount subsequences.
- Current character is not part of aCount subsequences.
- Therefore we do aCount = (1 + 2 * aCount);
- If current character is 'b', then there are following possibilities :
- Current character begins a new subsequence of b's with aCount subsequences.
- Current character is part of bCount subsequences.
- Current character is not part of bCount subsequences.
- Therefore we do bCount = (aCount + 2 * bCount);
- If current character is 'c', then there are following possibilities :
- Current character begins a new subsequence of c's with bCount subsequences.
- Current character is part of cCount subsequences.
- Current character is not part of cCount subsequences.
- Therefore we do cCount = (bCount + 2 * cCount);
- Finally we return cCount;
Explanation of approach with help of example:
Below is the implementation of above idea:
3
Complexity Analysis:
DP Based Approach:
Base Case: Set dp[0][0][0] = 1 as an empty string is also a valid subsequence.
DP Recurrence and Transition: Iterate through the string character by character. For each character s[idx]:
Update dp[i][j][k] based on the recurrence relation considering the current character:
If s[idx] == 'a', update dp[i+1][j][k] += dp[i][j][k] to account for 'a'.
If s[idx] == 'b', update dp[i][j+1][k] += dp[i][j][k] to account for 'b'.
If s[idx] == 'c', update dp[i][j][k+1] += dp[i][j][k] to account for 'c'.
Final Sub-problem: Finally, the count of subsequences of the form a^i b^j c^k where i >= 1, j >= 1, and k >= 1 will be stored in dp[n][n][n].
Complexity Analysis:
Time Complexity: O(n).
Auxiliary Space: O(n).
This article is contributed by Mr. Somesh Awasthi.