Magicsheet logo

Find the Punishment Number of an Integer

Medium
12.5%
Updated 8/1/2025

Find the Punishment Number of an Integer

1. What is this problem about?

The Find the Punishment Number of an Integer interview question is a mathematical search task with a recursive sub-problem. You are given an integer nn. For each number ii from 1 to nn, you calculate its square (i2i^2). The "punishment number" of nn is the sum of all i2i^2 such that the decimal string representation of i2i^2 can be partitioned into contiguous substrings that sum up to ii.

2. Why is this asked in interviews?

Companies like Google and Amazon ask the Find the Punishment Number coding problem to test a candidate's mastery of Backtracking and string-to-number manipulation. It requires a combination of iterative searching (for the outer sum) and a recursive "can-partition" check for each square. It evaluations your ability to handle nested logical structures.

3. Algorithmic pattern used

This problem follows the Backtracking interview pattern for partitioning.

  • Outer Loop: Iterate ii from 1 to nn.
  • Recursive Check: For each ii, check if i2i^2 is "punishable":
    • Convert i2i^2 to a string.
    • Use recursion to explore all ways to split the string into parts.
    • In each step, pick a substring of length LL, convert it to a number, and subtract it from the target value ii.
    • If you reach the end of the string and the target value becomes exactly 0, the number is valid.

4. Example explanation

i=10i = 10. i2=100i^2 = 100.

  • Can "100" sum to 10?
    • Split: "10" + "0". Sum: 10+0=1010 + 0 = 10. YES!
  • 10 is punishable. 102=10010^2 = 100 is added to the total punishment number. i=9i = 9. i2=81i^2 = 81.
  • Split "8" + "1" = 9. YES!
  • 9 is added.

5. Common mistakes candidates make

  • Ignoring leading zeros: Treating "0" as something that doesn't contribute to the sum. In this problem, "0" is a valid part of the partition.
  • Inefficient Partitioning: Using string slicing inside recursion instead of index-based pointers, which can slow down the execution.
  • Redundant Calculation: Failing to pre-calculate or cache the "punishable" property for numbers if nn is used across multiple test cases.

6. Interview preparation tip

Practice partitioning problems! If you can solve "Word Break" or "Palindrome Partitioning," the core logic of this problem will feel very familiar. Mastering Recursion on strings is a vital skill for technical rounds.

Similar Questions