Problem 906

Abstract / Summary

Find all superpalindromic numbers in a given range and return their count modulo 1e9 plus 7

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0906.py

class Solution:
    def superpalindromesInRange(self, left: str, right: str) -> int:
        left  = int(left)
        right = int(right)

        def ispalindrome(n):
            s = str(n)
            return s == s[::-1]

        result = 0
        for half in range(1, 22222+1): # sqrt(10^18) = 10^9, so one half has at most 5 digits
                                       # actually all digits seem always to be in [0,1,2], except for half=3
            s = str(half)

            odd  = int(s[:-1] + s[::-1])
            odd2 = odd * odd
            if left <= odd2 <= right and ispalindrome(odd2):
                result += 1

            if len(s) < 5: # len(s) == 5 yields 2*2*5=20 digits in the super-palindrome => too big
                even  = int(s + s[::-1])
                even2 = even * even
                if left <= even2 <= right and ispalindrome(even2):
                    result += 1

        return result
26 lines | 957 bytes | submitted September 28, 2023 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (70k+ submissions).

Typical patterns to solve this problem:
  • Enumeration
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method superpalindromesInRange. The method receives two numeric bounds as strings, converts them to integers, and counts how many “super-palindromes” lie within the inclusive interval. A super-palindrome is a number that is itself a palindrome and whose square root is also a palindrome. The algorithm generates candidate palindromic roots, squares them, and verifies both the range constraint and the palindrome property of the square.

Core Logic

Input conversion

left  = int(left)
right = int(right)

The string arguments are immediately transformed into integer values, allowing arithmetic and comparison operations without further casting.

Palindrome test helper

def ispalindrome(n):
    s = str(n)
    return s == s[::-1]

A small inner function converts a number to its decimal representation and checks equality with its reversed string. This utility is used for both the root and the squared value.

Generation of palindromic roots

The algorithm iterates over a range of “half” values that represent the first half of a palindrome. The loop bound is set to 22222+1. The comment explains that the square root of the largest possible super-palindrome (10^18) has at most nine digits, and therefore a half segment of five digits is sufficient.

for half in range(1, 22222+1):
    s = str(half)

The string s holds the decimal digits of the current half. Two distinct constructions are performed: one for odd-length palindromes and one for even-length palindromes.

Odd-length palindrome root

odd  = int(s[:-1] + s[::-1])
odd2 = odd * odd
if left <= odd2 <= right and ispalindrome(odd2):
    result += 1

The expression s[:-1] + s[::-1] drops the last character of s before mirroring, producing a palindrome with an odd number of digits. The resulting integer odd is squared to obtain odd2. The code then checks that odd2 falls inside the requested interval and that odd2 itself is a palindrome before incrementing the counter.

Even-length palindrome root

The even case is guarded by a length check to avoid generating roots that would produce squares exceeding the 10^18 limit.

if len(s) < 5:
    even  = int(s + s[::-1])
    even2 = even * even
    if left <= even2 <= right and ispalindrome(even2):
        result += 1

Here s + s[::-1] mirrors the entire half, yielding an even-length palindrome. The same validation steps as in the odd case are applied.

Result return

return result

After exhausting all candidate halves, the method returns the total count of super-palindromes found.

Edge Cases Handled

The code explicitly addresses the situation where the generated palindrome root would be too large to produce a valid square. By limiting the even-length construction to halves with fewer than five digits, it prevents creation of 20-digit squares, which would exceed the maximum bound of 10^18.

The range check left <= odd2 <= right (and similarly for even2) ensures that numbers outside the user-specified interval are ignored, even if they satisfy the palindrome property.

The palindrome test is applied to the squared value rather than the root, guaranteeing that only numbers that are palindromes in both forms are counted.

The loop starts at 1, thereby excluding the trivial root 0. Since 0 squared is 0, which would be a valid super-palindrome only if the lower bound includes 0, the implementation deliberately omits this case, aligning with typical problem specifications that consider positive integers.

Performance Optimizations

The algorithm avoids brute-force enumeration of every integer between left and right. Instead, it constructs only those numbers that can possibly be super-palindromes by generating palindromic roots directly. This dramatically reduces the search space because the number of palindromic roots up to 10^9 is on the order of tens of thousands, far fewer than the billions of candidates that a naïve scan would examine.

String slicing and reversal (s[::-1]) are used to build palindromes in constant time per iteration, leveraging Python’s efficient slice operations. The early length guard for even-length roots eliminates unnecessary calculations for halves that would inevitably produce out-of-range squares, saving both CPU cycles and memory for large inputs.

The inner palindrome check ispalindrome works on the string representation of the squared number, which is a fast operation given the relatively small number of candidates that reach this point. By performing the range check before the palindrome test, the code avoids the cost of string conversion for numbers that are already known to be outside the interval.

Overall, the combination of targeted candidate generation, early pruning based on length, and ordering of cheap checks before expensive ones yields a solution that runs quickly even for the maximal input range.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a magical mirror that reflects numbers. A palindrome is a special number that looks exactly the same when you read it forward or backward, just like how the word dad looks the same from both ends. This code is on a treasure hunt for super numbers. First, it takes two starting points to define a space where it should look for these treasures. It starts creating smaller numbers and reflecting them like a mirror to make them into bigger numbers. After making these new bigger numbers, it multiplies them by themselves to see if they grow into the super numbers the program is looking for. It checks if the new big number is a palindrome by flipping it to see if it stays the same. If the number is a palindrome and it stays within the boundaries provided at the beginning, it counts that number as a success. It repeats this process over and over by building different patterns until it finishes checking all the possibilities.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.44 | σ = 1.77

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
27 links | 14 authors | 8 languages

Videos

1 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

32 solutions   September 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality