1812. Digit Power Echoes
A number is an echo of its digits when it equals the sum of its own digits, each raised to the power p. For example, with p = 3 the number 153 is an echo because 1^3 + 5^3 + 3^3 = 153. Only positive numbers with no leading zero are considered, so a number with n digits lies between 10^(n-1) and 10^n - 1 (for n = 1 the candidates are 1 to 9).
Return, in ascending order, every echo that has exactly n digits, or an empty array if there is none. Scanning all n-digit numbers is far too slow for n = 10. The power sum depends only on which digits are used and how often, not on their order, so it is enough to try each multiset of n digits once and check whether the resulting sum is made of exactly those digits. This is about C(n + 9, 9) candidates, with O(n) extra space apart from the answer.
Example 1
- Input:
- n = 3, p = 3
- Output:
- [153,370,371,407]
- Explanation:
153, 370, 371 and 407 each equal the sum of the cubes of their digits (for example 1 + 125 + 27 = 153).
Example 2
- Input:
- n = 4, p = 4
- Output:
- [1634,8208,9474]
- Explanation:
1634, 8208 and 9474 equal the sums of the fourth powers of their digits.
Example 3
- Input:
- n = 2, p = 3
- Output:
- []
- Explanation:
No two-digit number equals the sum of the cubes of its digits, so the result is empty.
Constraints
1 ≤ n ≤ 10
1 ≤ p ≤ 12 (every power sum stays below 3 * 1012)
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(C(n + 9, 9) * n)
- Space
- O(n)