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 equalsi
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= n <= 1000
Solution
Method 1 - Backtracking
To solve the problem, we need to:
- Calculate the square of every integer
i
where1 <= i <= n
. - Check if the square of
i
can be partitioned into contiguous substrings such that the sum of these substrings equalsi
. - If the above condition is satisfied, include
i*i
in the punishment number, which is the final sum.
Here is the approach to check the partition condition:
- Convert the square of a number (
i * i
) to a string to facilitate substring manipulation. - Use recursion or backtracking to check all possible ways of partitioning the string representation of the square. If any partition’s sum equals
i
, we include the value in the answer.
Here is how the state space tree for backtracking for i
= 36 and i^2
= 1296.
graph TD A["1296"] --> B1["1"] A --> B2["12"] A --> B3["129"] A --> B4["1296"]:::endNode B1 --> C1["2"] B1 --> C2["29"] B1 --> C3["296"]:::endNode C1 --> D1["9"] C1 --> D2["96"]:::endNode D1 --> E1["6"]:::endNode C2 --> D3["6"]:::success B2 --> C4["9"] B2 --> C5["96"]:::endNode C4 --> D4["6"]:::endNode B3 --> C6["6"]:::endNode %% Class Definitions for Styling %% classDef success fill:#d4f5d4,stroke:#34a853,stroke-width:2px,color:#34a853; classDef endNode fill:#ffe6e6,stroke:#ff4d4d,stroke-width:2px,color:#ff4d4d;
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * 2^d)
, where isd
is the number of digits in number on average. For a single numberi
:- Calculating
i * i
isO(d)
, whered
is the number of digits in the square ofi
. - Checking valid partitions with backtracking is
O(2^d)
because there are2^d
possible ways to splitd
digits. Considering all numbers1
ton
, the total complexity becomes approximatelyO(n * 2^d)
, whered
is the number of digits in the largest square.
- Calculating
- 🧺 Space complexity:
O(d)