Python 2396.py
class Solution:
def isStrictlyPalindromic(self, n: int) -> bool:
for b in range(2, n - 2 + 1):
digits = []
x = n
while x > 0:
digits.append(x % b)
x //= b
if digits != reversed(digits):
return False
return True
Difficulty
and has an acceptance rate of about 90% (200k+ submissions).
Typical patterns to solve this problem:
- Math
- Two Pointers
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 isStrictlyPalindromic. The method receives an integer n and determines whether the representation of n is a palindrome in every base b ranging from 2 up to n-2 inclusive. The algorithm iterates through each candidate base, converts n to that base, and checks the digit sequence for palindromic symmetry. If any base yields a non-palindromic representation, the method returns False; otherwise it returns True after all bases have been examined.
Key Steps
The first logical block establishes the range of bases to be examined. The loop header for b in range(2, n - 2 + 1): iterates from the smallest permissible base (2) up to n-2. The addition of + 1 compensates for Python’s exclusive upper bound in range, ensuring that n-2 itself is included in the iteration.
for b in range(2, n - 2 + 1):
Inside the loop, the conversion of n to base b is performed manually. An empty list digits is created to collect the remainders. The variable x is initialized with the value of n. A while loop extracts the least-significant digit by computing x % b and appends it to digits. The integer division x //= b discards the processed digit, and the loop continues until x becomes zero, at which point digits holds the full representation of n in reverse order (least-significant digit first).
digits = []
x = n
while x > 0:
digits.append(x % b)
x //= b
After the conversion, the code checks whether the digit list reads the same forward and backward. The expression digits != reversed(digits) compares the original list with an iterator that yields the elements in reverse order. If the two sequences differ, the method concludes that the current base does not produce a palindrome and returns False immediately, short-circuiting further computation.
if digits != reversed(digits):
return False
If the loop completes without triggering a return, the method reaches the final statement return True, indicating that every examined base produced a palindromic representation.
return True
Edge Cases Handled
The algorithm implicitly handles the situation where n is less than 4. In such cases the range range(2, n - 2 + 1) becomes empty because the start value (2) exceeds the end value. Consequently, the for loop body never executes, and the method proceeds directly to return True. This behavior aligns with the definition of a strictly palindromic number, which requires checking bases up to n-2; when no bases exist, the condition is vacuously satisfied.
Another edge case concerns the conversion loop when n equals zero. Although the problem constraints typically exclude zero, the while x > 0 guard ensures that the loop body is skipped for x == 0, leaving digits empty. The subsequent palindrome check compares an empty list with its reversed iterator, which evaluates as equal, preserving correctness for this degenerate input.
The use of reversed(digits) rather than constructing a new list avoids altering the original digit order, thereby preserving the data needed for any subsequent logic (though none follows in this implementation). The comparison works correctly even when digits contains a single element, as a single-digit number is trivially a palindrome.
Performance Optimizations
The code employs an early-exit strategy: as soon as a non-palindromic base is detected, the method returns False without processing the remaining bases. This short-circuiting can dramatically reduce runtime for inputs that fail the condition early in the base range.
The manual base conversion avoids the overhead of string conversion functions and intermediate representations. By directly appending integer remainders to a list, the algorithm minimizes memory allocations and leverages integer arithmetic, which is generally faster than string manipulation.
The comparison digits != reversed(digits) uses the built-in reversed iterator, which yields elements on demand without creating a full reversed copy of the list. This approach reduces temporary memory usage, especially for large digit sequences that could arise when n is large and the base is small.
Collectively, these choices keep the execution path tight: a simple loop for base iteration, an in-place digit extraction loop, and an immediate comparison that can abort further work. The design therefore balances clarity with efficient use of Python’s built-in constructs.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of blocks numbered n. A palindrome is a special kind of sequence that looks the same whether you read it from the front or from the back, like the word mom. The code looks at the number n and changes it into different base systems, starting from base two all the way up to a base that is two smaller than the number itself.
For every base it picks, it breaks the number into a list of smaller pieces. Think of this like taking a long tower of blocks and creating smaller piles based on the size of the base. It saves those pieces in a list called digits. Then, it checks to see if the order of those digits is exactly the same forward and backward. If it finds even one base where the digits do not make a palindrome, it decides that the number is not special. If it checks every single one of those bases and every single one is a palindrome, then the number passes the test.
Code Quality
Complexity Analysis
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 | Java | Python | C++ | TS | ||||
| WalkCCC | Java | Python | C++ | ||||||
| leetcode.ca | Java | Python | Go | C++ | C | Rust | TS | ||
| Progiez | Java | Python | C++ | ||||||
| github | chandansgowda | Python | |||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| muhammadfarhankt | Go | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| muhammadfarhankt | Go | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 877: Stone Game
Solved On The Same Day
- problem 598: Range Addition II
- problem 653: Two Sum IV - Input is a BST
- problem 1470: Shuffle the Array
- problem 1512: Number of Good Pairs
- problem 1920: Build Array from Permutation
- problem 1929: Concatenation of Array
- problem 396: Rotate Function
- problem 877: Stone Game
- problem 1033: Moving Stones Until Consecutive
- problem 1402: Reducing Dishes
- problem 1406: Stone Game III
- problem 1463: Cherry Pickup II
- problem 1510: Stone Game IV
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