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

Leetcode #906: Super Palindromes

In this guide, we solve Leetcode #906 Super Palindromes 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

Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome. Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Math, String, Enumeration

Intuition

There is a mathematical invariant or formula that directly leads to the result.

Using math avoids unnecessary loops and reduces complexity.

Approach

Derive the formula or update rule, then compute the answer directly.

Handle edge cases like overflow or zero carefully.

Steps:

  • Identify the math relationship.
  • Compute the result with a loop or formula.
  • Handle edge cases.

Example

Input: left = "4", right = "1000" Output: 4 Explanation: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.

Python Solution

ps = [] for i in range(1, 10**5 + 1): s = str(i) t1 = s[::-1] t2 = s[:-1][::-1] ps.append(int(s + t1)) ps.append(int(s + t2)) class Solution: def superpalindromesInRange(self, left: str, right: str) -> int: def is_palindrome(x: int) -> bool: y, t = 0, x while t: y = y * 10 + t % 10 t //= 10 return x == y l, r = int(left), int(right) return sum(l <= x <= r and is_palindrome(x) for x in map(lambda x: x * x, ps))

Complexity

The time complexity is O(M14×log⁡M)O(M^{\frac{1}{4}} \times \log M)O(M41​×logM), and the space complexity is O(M14)O(M^{\frac{1}{4}})O(M41​). The space complexity is O(M14)O(M^{\frac{1}{4}})O(M41​).

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