#2698

Find the Punishment Number of an Integer

Medium
MathBacktrackingBacktrackingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m²)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m²)Space O(n * m)

The optimal solution leverages memoization to avoid recalculating partitions for the same substrings. This significantly reduces the number of recursive calls and speeds up the process.

⚙️

Algorithm

7 steps
  1. 1Step 1: Initialize a variable to hold the punishment number sum.
  2. 2Step 2: Create a memoization dictionary to store results of previously computed partitions.
  3. 3Step 3: Loop through each integer i from 1 to n.
  4. 4Step 4: Calculate i * i and convert it to a string.
  5. 5Step 5: Use the memoization function to check if the square can be partitioned to sum to i.
  6. 6Step 6: If it can, add i * i to the punishment number sum.
  7. 7Step 7: Return the total punishment number sum.
solution.py20 lines
1def punishment_number(n):
2    memo = {}
3    def can_partition(s, target):
4        if (s, target) in memo:
5            return memo[(s, target)]
6        if not s:
7            return target == 0
8        for i in range(1, len(s) + 1):
9            if can_partition(s[i:], target - int(s[:i])):
10                memo[(s, target)] = True
11                return True
12        memo[(s, target)] = False
13        return False
14
15    punishment_sum = 0
16    for i in range(1, n + 1):
17        square_str = str(i * i)
18        if can_partition(square_str, i):
19            punishment_sum += i * i
20    return punishment_sum

Complexity note: The time complexity is O(n * m²) where n is the number of integers and m is the maximum length of the square string representation. The space complexity is O(n * m) due to the memoization dictionary storing results for each substring and target combination.

  • 1Understanding how to partition strings is crucial for solving this problem.
  • 2Using memoization can drastically improve performance by avoiding redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.