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
Difficulty
and has an acceptance rate of about 40% (70k+ submissions).
Typical patterns to solve this problem:
- Enumeration
- Math
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 912: Sort an Array
- problem 923: 3Sum With Multiplicity
- problem 973: K Closest Points to Origin
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
- problem 1366: Rank Teams by Votes
- problem 1419: Minimum Number of Frogs Croaking
- problem 1738: Find Kth Largest XOR Coordinate Value
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 992: Subarrays with K Different Integers
- problem 1106: Parsing A Boolean Expression
- problem 1601: Maximum Number of Achievable Transfer Requests
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
Extra
- 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