Problem 2396

Abstract / Summary

A number is strictly palindromic if every digit except the middle one in its decimal form appears an even number of times.

Note

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

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
12 lines | 340 bytes | submitted October 3, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 90% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
  • Two Pointers
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 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.

written by openai gpt

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.

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 = 4 | μ = 4.41 | σ = 1.93

Complexity Analysis

not analyzed yet

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 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
23 links | 10 authors | 8 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

6 easy 3 medium 4 hard
14 solutions   October 3, 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