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. Your task is to find the sum of power of all subsequences of the array.
The power of any subsequence is defined as the number of its sub-subsequences that sum to k. For example, if a subsequence is [2, 3, 5] and k = 5, then its power is the count of all combinations from [2, 3, 5] that sum to 5 (which would be [2, 3] and [5], so power = 2).
Since the final answer can be extremely large, return it modulo 109 + 7.
Example: If nums = [1, 2, 3] and k = 3, we need to:
- Find all possible subsequences of
[1, 2, 3] - For each subsequence, count how many of its sub-subsequences sum to 3
- Sum all these counts together
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1, 2, 3], k = 3
โบ
Output:
6
๐ก Note:
All subsequences: [1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]. For [3]: sub-subsequences are [],[3] โ power=1 (only [3] sums to 3). For [1,2]: sub-subsequences are [],[1],[2],[1,2] โ power=1 (only [1,2] sums to 3). For [1,2,3]: 8 sub-subsequences, power=3 ([3],[1,2] sum to 3). Total = 1+1+3+1 = 6
example_2.py โ Small Values
$
Input:
nums = [2, 3, 3], k = 5
โบ
Output:
4
๐ก Note:
Subsequence [2,3] appears twice (using first or second 3), each contributing 1 to power. Subsequence [2,3,3] has sub-subsequences that sum to 5: [2,3] (2 ways). Total power = 1+1+2 = 4
example_3.py โ Edge Case
$
Input:
nums = [1], k = 1
โบ
Output:
1
๐ก Note:
Only one subsequence [1]. Its sub-subsequences are [] (sum=0) and [1] (sum=1). Only [1] sums to k=1, so power=1. Total=1
Constraints
- 1 โค nums.length โค 100
- 1 โค nums[i] โค 100
- 1 โค k โค 100
- Answer fits in 32-bit integer after modulo operation
Visualization
Tap to expand
Understanding the Visualization
1
Form Committees
Each subsequence is like a committee that decides which treasure chests to consider
2
Create Maps
Each committee creates all possible treasure maps from their chosen chests
3
Count Winning Maps
For each committee, count how many maps lead to exactly k coins
4
Sum All Powers
Add up the power (winning map count) from all committees
Key Takeaway
๐ฏ Key Insight: Use dynamic programming to count element contributions across all subsequences simultaneously, avoiding the exponential cost of explicit generation.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code