Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2698: Find the Punishment Number of an Integer

In this guide, we solve Leetcode #2698 Find the Punishment Number of an Integer in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Math, Backtracking

Intuition

We must explore combinations of choices, but many branches can be pruned early.

Backtracking enumerates valid candidates while keeping the search space under control.

Approach

Use DFS to build candidates step by step, and backtrack when constraints are violated.

Pruning keeps the exploration practical for typical constraints.

Steps:

  • Define the decision tree.
  • DFS through choices and backtrack.
  • Prune invalid paths early.

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: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10. Hence, the punishment number of 10 is 1 + 81 + 100 = 182

Python Solution

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

The time complexity is O(n1+2log⁡102)O(n^{1 + 2 \log_{10}^2})O(n1+2log102​), and the space complexity is O(log⁡n)O(\log n)O(logn), where nnn is the given positive integer. The space complexity is O(log⁡n)O(\log n)O(logn), where nnn is the given positive integer.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy