#3082

Find the Sum of the Power of All Subsequences

Hard
ArrayDynamic ProgrammingDynamic ProgrammingSubset Sum Problem
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k)
Space
O(1)
O(k)
💡

Intuition

Time O(n * k)Space O(k)

The optimal solution uses dynamic programming to count the number of subsequences that sum to k. This approach is efficient because it avoids generating all subsequences and instead builds up the solution using previously computed results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array of size k+1 to store counts of subsequences that sum to each index.
  2. 2Step 2: For each number in nums, update the DP array from back to front to avoid overwriting results from the current iteration.
  3. 3Step 3: The value at DP[k] will give the total count of subsequences that sum to k.
solution.py8 lines
1def sum_of_power(nums, k):
2    MOD = 10**9 + 7
3    dp = [0] * (k + 1)
4    dp[0] = 1  # Base case: one way to make sum 0 (empty subsequence)
5    for num in nums:
6        for j in range(k, num - 1, -1):
7            dp[j] = (dp[j] + dp[j - num]) % MOD
8    return dp[k]

Complexity note: The time complexity is O(n * k) because we iterate through each number and update the DP array for each possible sum up to k. The space complexity is O(k) due to the DP array.

  • 1Subsequences can be counted using dynamic programming to avoid exponential time complexity.
  • 2The number of ways to form a sum can be built incrementally using previously computed results.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.