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: nums=[1,2,1], k=2Input[1, 2, 1]Process: Calculate Power for Each Subsequence[] → 0 ways to sum to 2[1] → 0 ways to sum to 2[2] → 1 way to sum to 2 ([2])[1] → 0 ways to sum to 2[1,2] → 1 way to sum to 2 ([2])[1,1] → 1 way to sum to 2 ([1,1])[2,1] → 1 way to sum to 2 ([2])[1,2,1] → 2 ways ([2], [1,1])Output6Total Power = 0 + 0 + 1 + 0 + 1 + 1 + 1 + 2 = 6
Understanding the Visualization
1
Input
Array [1,2,1] with target sum k=2
2
Process
For each subsequence, count ways to sum to k
3
Output
Sum all powers: 6
Key Takeaway
🎯 Key Insight: Each element can contribute to current subsequence or be saved for future ones, leading to exponential state space
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