Ways to Express an Integer as Sum of Powers - Problem
Problem Statement: Given two positive integers n and x, find the number of ways to express n as the sum of xth powers of unique positive integers.

In other words, you need to count all possible sets [n1, n2, ..., nk] where:
• All elements are unique positive integers
n = n1^x + n2^x + ... + nk^x

Example: If n = 160 and x = 3, one valid way is 2³ + 3³ + 5³ = 8 + 27 + 125 = 160.

Note: Since the result can be very large, return it modulo 10⁹ + 7.

Input & Output

example_1.py — Basic Case
$ Input: n = 10, x = 2
Output: 1
💡 Note: Only one way: 1² + 3² = 1 + 9 = 10. Note that 2² + 6² would exceed our constraint since we need unique positive integers and their sum of squares must equal 10.
example_2.py — Multiple Ways
$ Input: n = 160, x = 3
Output: 1
💡 Note: One way: 2³ + 3³ + 5³ = 8 + 27 + 125 = 160. This demonstrates finding a combination of three unique cubes that sum to the target.
example_3.py — Small Input
$ Input: n = 1, x = 1
Output: 1
💡 Note: Only one way: use the number 1 itself (1¹ = 1). This is the simplest case where we need just one number to reach our target.

Visualization

Tap to expand
Magical Stones Collection ProblemGoal: Find ways to collect unique stones with total weight = n1weight: 1^x2weight: 2^x3weight: 3^xkweight: k^xDP Process:For each stone i: dp[total_weight] += dp[total_weight - stone_i_weight]Example with n=10, x=2:Stone 1 (weight=1): Can contribute to sums 1,2,3,4,5,6,7,8,9,10Stone 2 (weight=4): Can contribute to sums 4,5,6,7,8,9,10Stone 3 (weight=9): Can contribute to sums 9,10🎯 Key Insight: Process stones one by oneUpdate DP array backwards to ensure each stone used at most once
Understanding the Visualization
1
Find Available Stones
Identify all stones (numbers) whose weight (x-th power) doesn't exceed n
2
DP Decision Process
For each stone, decide: include it in our collection or skip it
3
Update Possibilities
Update count of ways to achieve each possible total weight
4
Final Count
Return the number of ways to achieve exactly weight n
Key Takeaway
🎯 Key Insight: Dynamic programming transforms this combinatorial problem into an efficient counting process by building up solutions incrementally, ensuring each number is used at most once through backward iteration.

Time & Space Complexity

Time Complexity
⏱️
O(n × k)

Where k is the largest number such that k^x ≤ n. We iterate through k numbers and for each, update up to n DP states.

n
2n
Linear Growth
Space Complexity
O(n)

DP array of size n+1 to store number of ways for each sum

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 300
  • 1 ≤ x ≤ 5
  • All integers are positive
  • Numbers in the sum must be unique
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
21.5K Views
Medium Frequency
~25 min Avg. Time
890 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