![]() |
VOOZH | about |
Given an array vec[] of size N of non-negative integers. The task is to count the number of subsequences with the sum equal to S - 2 where S is the sum of all the elements of the array.
Examples:
Input: vec[] = {2, 0, 1, 2, 1}, N=5
Output: 6
Explanation: {2, 0, 1, 1}, {2, 1, 1}, {2, 0, 2}, {2, 2}, {0, 1, 2, 1}, {1, 2, 1}Input: vec[] = {2, 0, 2, 3, 1}, N=5
Output: 4
Explanation: {2, 0, 3, 1}, {2, 3, 1}, {0, 2, 3, 1}, {2, 3, 1}
Naive Approach: The idea is to generate all subsequences and check the sum of each and every individual subsequence equals S-2 or not.
Below is the implementation of the above approach.
6
Time Complexity: O(2N)
Auxiliary Space: O(1)
Efficient Approach: The idea is to use the Combinatorics that apart from 0's, 1's, and 2's, all the other elements in our array will be part of the desired subsequences. Let's call them extra elements. Then, count the occurrences of 0's, 1's, and 2's in the array. Let's say the count of 0's is x, count of 1's be y, count of 2's be z.
- Let's count the number of desired subsequences if all 2's and extra elements are in the subsequence. Now there can be exactly y - 2 elements out of y. Note that there is no restriction for taking 0's as it contributes nothing to our subsequence sum.
- Hence, the total count of such subsequences = count1 = 2x × yCy - 2 = 2x × yC2 ( Since, nC0 + nC1 + . . . + nCn = 2n).
- Let's count the number of subsequences if all the 1's are in our subsequence. Now there can be exactly z - 1 elements out of z.
- Hence, the total count of such subsequences = count2 = 2x × zCz - 1 = 2x × zC1
- Total count of subsequences whose sum is equal to S - 2, count = count1 + count2 = 2x × ( yC2 + zC1 )
Follow the steps below to solve the problem:
Below is the implementation of the above approach.
6
Time Complexity: O(N)
Auxiliary Space: O(1)