VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-subsequences-with-sum-two-less-than-the-array-sum/

⇱ Count of subsequences with sum two less than the array sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of subsequences with sum two less than the array sum

Last Updated : 23 Jul, 2025

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.


Output
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 = 2 × 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:

  • Initialize the variable sum as the sum of the array.
  • Initialize the variable answer as 0 to store the answer.
  • Initialize the variables countOfZero, countOfOne and countOfTwo to store the count of 0, 1 and 2.
  • Traverse the array vec[] using the iterator x and perform the following tasks:
    • Count the occurrences of 0's, 1's, and 2's.
  • Initialize the variables value1 as 2countOfZero.
  • Initialize the variable value2 as (countOfOne * (countOfOne - 1)) / 2.
  • Initialize the variable value3 as countOfTwo.
  • Set the value of answer as value1 * ( value2 + value).
  • After performing the above steps, print the value of answer as the answer.

Below is the implementation of the above approach.


Output
6

Time Complexity: O(N) 
Auxiliary Space: O(1)

Comment
Article Tags: