Find the Punishment Number of an Integer - 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.

Input & Output

Example 1 — Basic Case
$ Input: n = 10
Output: 182
💡 Note: Numbers 1, 9, 10 satisfy the condition: 1²=1 ("1"→1), 9²=81 ("8"+"1"→9), 10²=100 ("10"+"0"→10 or "1"+"00" invalid). Sum: 1+81+100=182
Example 2 — Small Input
$ Input: n = 37
Output: 1478
💡 Note: All valid numbers up to 37 whose squares can be partitioned to sum back to the original number

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
Punishment Number Algorithm INPUT n = 10 Check integers 1 to n: 1 2 3 ... 10 For each i, compute i*i: 1*1 = 1 9*9 = 81 10*10 = 100 Valid punishment numbers: i=1: 1 = 1 [OK] i=9: 8+1 = 9 [OK] i=10: 1+0+0 = 1 [NO] ALGORITHM STEPS 1 Initialize sum = 0 Set punishment number to 0 2 Loop i from 1 to n Compute square = i * i 3 Partition Check Use memoization to check if substrings sum to i 4 Add to sum If valid, sum += i*i Memoization Example (i=9): "81" --> partition check Try: "8"+"1" = 8+1 = 9 Match! Cache result canPartition(81,9) = true Memo: {(81,9): true} FINAL RESULT Valid integers found: i = 1: 1*1 = 1 "1" = 1 [OK] +1 i = 9: 9*9 = 81 "8"+"1" = 9 [OK] +81 Calculation: sum = 1 + 81 sum = 82 Also valid: i=10 --> 100 "10"+"0" or "1"+"00" --> 10 OUTPUT 182 Key Insight: Memoization optimizes by caching partition results. For each number i*i, we recursively try all possible substring splits. The memo stores (remaining_string, target_sum) pairs to avoid recomputation. Time complexity reduces from exponential to O(n * d^2) where d = digits in n*n. TutorialsPoint - Find the Punishment Number of an Integer | Optimized with Memoization
Asked in
Google 15 Microsoft 10
8.5K Views
Medium Frequency
~25 min Avg. Time
245 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