Find the Punishment Number of an Integer Problem
#2698
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2698.
Given a positive integer n, return the punishment number of n.
The punishment number of n is defined as the sum of the squares of all integers i such that:
1 <= i <= n- The decimal representation of
i * ican be partitioned into contiguous substrings such that the sum of the integer values of these substrings equalsi.
Example 1:
Input: n = 10
Output: 182
Explanation: There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement:
- 1 since 1 * 1 = 1
- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9.
- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10.
Hence, the punishment number of 10 is 1 + 81 + 100 = 182
Example 2:
Input: n = 37
Output: 1478
Explanation: There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement:
- 1 since 1 * 1 = 1.
- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1.
- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0.
- 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6.
Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478
Constraints:
1 <= n <= 1000
Solution
Approach: Enumeration with DFS
For each i from 1 to n, write i * i in decimal and try to cut it into consecutive pieces whose values add up to i. A DFS tries every cut position: take the next piece s[i..j], subtract its value from the remaining target, and recurse on the rest. It stops a branch as soon as the piece is larger than the remaining target. When i works, add i * i to the answer.
Complexity: Each square has at most 7 digits, so at most 26 ways to cut it: about O(n) time overall with a large constant, and O(log n) extra space.
class Solution:
def punishmentNumber(self, n: int) -> int:
def check(s: str, i: int, x: int) -> bool:
m = len(s)
if i >= m:
return x == 0
y = 0
for j in range(i, m):
y = y * 10 + int(s[j])
if y > x:
break
if check(s, j + 1, x - y):
return True
return False
ans = 0
for i in range(1, n + 1):
x = i * i
if check(str(x), 0, i):
ans += x
return ans