Find the Sum of the Power of All Subsequences - Problem

You are given an integer array nums of length n and a positive integer k.

The power of an array of integers is defined as the number of subsequences with their sum equal to k.

Return the sum of power of all subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1], k = 2
Output: 6
💡 Note: Subsequences and their powers: [] has 0 ways, [1] has 0 ways, [2] has 1 way (itself), [1] has 0 ways, [1,2] has 1 way ([2]), [1,1] has 1 way ([1,1]), [2,1] has 1 way ([2]), [1,2,1] has 2 ways ([2] and [1,1]). Total: 0+0+1+0+1+1+1+2 = 6
Example 2 — Single Element
$ Input: nums = [1], k = 1
Output: 1
💡 Note: Only one subsequence [1] which has 1 way to sum to k=1 (the element itself). Total power: 1
Example 3 — No Valid Sums
$ Input: nums = [2,3], k = 1
Output: 0
💡 Note: Subsequences: [] (0 ways), [2] (0 ways), [3] (0 ways), [2,3] (0 ways). No subsequence can sum to k=1. Total: 0

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100
  • 1 ≤ k ≤ 100

Visualization

Tap to expand
Sum of Power of All Subsequences INPUT nums array: 1 i=0 2 i=1 1 i=2 Input Values: nums = [1, 2, 1] k = 2 (target sum) All Subsequences: [], [1], [2], [1] [1,2], [1,1], [2,1] [1,2,1] Valid sums=2: [2], [1,1], [1,1] n=3, total 2^3=8 subsequences ALGORITHM (DP) 1 Initialize DP dp[j] = ways to form sum j dp[0] = 1, others = 0 2 Process Each num Include or exclude element contribution: 2^(n-1) 3 Update DP Table For j from k down to num dp[j] += dp[j-num] 4 Calculate Power Each subseq with sum=k contributes 2^remaining DP Table Evolution sum: 0 1 2 init: 1 0 0 +[1]: 1 1 0 +[2]: 1 1 1 +[1]: 1 2 2 FINAL RESULT Subsequences with sum=2: [2] appears in 2^2=4 superseqs [1,1] (i=0,2) appears in 2^1=2 superseqs Note: two [1,1] combinations from indices (0,2) Power Calculation: [2]: 4 supersequences [1,1]: 2 x 1 = 2 Output: 6 4 + 2 = 6 (mod 10^9+7) Key Insight: For each subsequence S with sum=k, count supersequences containing S. If S has m elements, there are 2^(n-m) supersequences. Use DP to track ways to form each sum while accumulating the contribution of each element's inclusion. Time: O(n*k), Space: O(k). TutorialsPoint - Find the Sum of the Power of All Subsequences | Dynamic Programming Approach
Asked in
Google 15 Microsoft 12 Amazon 8
8.9K Views
Medium Frequency
~45 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen