Find the Punishment Number of an Integer — LeetCode 2698 Python Solution

MediumMathBacktracking
Problem
#2698
Reading time
4 min

The problem

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 * i can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i.

Example

Input
n = 10
Output
182
Explanation
There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n^{1 + 2 \log_{10}^2})
SpaceO(\log n), where n is the given positive integer auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 2698. Find the Punishment Number of an Integer is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2698. Find the Punishment Number of an Integer?
LeetCode 2698. Find the Punishment Number of an Integer is rated Medium on LeetCode.
What is the time complexity of LeetCode 2698. Find the Punishment Number of an Integer?
The Python solution on this page runs in O(n^{1 + 2 \log_{10}^2}).
What is the space complexity of LeetCode 2698. Find the Punishment Number of an Integer?
The Python solution on this page uses O(\log n), where n is the given positive integer auxiliary space.
What topics does LeetCode 2698. Find the Punishment Number of an Integer cover?
LeetCode 2698. Find the Punishment Number of an Integer is tagged Math and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview