Facebook Pixel

2396. Strictly Palindromic Number

Problem Description

Given an integer n, you need to determine if it is strictly palindromic.

An integer n is considered strictly palindromic if its string representation is palindromic in every base b where b ranges from 2 to n - 2 (inclusive).

A string is palindromic if it reads the same forward and backward (like "121" or "abba").

For example, to check if a number is strictly palindromic:

  • Convert the number to each base from 2 to n - 2
  • Check if each representation is a palindrome
  • Return true only if ALL representations are palindromes

The solution reveals an interesting mathematical insight: no integer n ≥ 4 can be strictly palindromic. This is because:

  • When n = 4, its binary (base-2) representation is 100, which is not a palindrome
  • When n > 4, its representation in base (n - 2) is always 12, which is not a palindrome (since n in base (n - 2) equals 1 × (n - 2) + 2)

Therefore, the function always returns false.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

At first glance, this problem seems like it requires converting a number to multiple bases and checking palindromes for each. However, let's think about what happens when we convert a number n to different bases.

For small values of n (like n = 4), we can manually check that the binary representation 100 is not a palindrome, so it fails immediately.

For larger values, consider what happens when we convert n to base (n - 2). In any base b, when we convert a number that's slightly larger than b, we get a small representation. Specifically, when we convert n to base (n - 2):

  • n = 1 × (n - 2) + 2
  • This gives us the representation 12 in base (n - 2)

The string 12 is clearly not a palindrome. This means for any n > 4, when we check base (n - 2), we'll always get 12, which fails the palindrome test.

Since the problem requires the number to be palindromic in every base from 2 to (n - 2), and we've shown that it always fails for at least one base (either base 2 when n = 4, or base (n - 2) when n > 4), no number can be strictly palindromic.

This mathematical insight allows us to skip all the conversion and palindrome checking logic entirely and simply return false for any input.

Learn more about Math and Two Pointers patterns.

Solution Approach

The implementation is remarkably simple because of the mathematical proof we discovered. Instead of implementing the naive approach of converting to multiple bases and checking palindromes, we can directly return false.

Here's why this works:

Case 1: When n = 4

  • We need to check bases from 2 to 2 (since n - 2 = 2)
  • In base 2: 4 converts to 100
  • 100 is not a palindrome
  • Therefore, 4 is not strictly palindromic

Case 2: When n > 4

  • We need to check bases from 2 to (n - 2)
  • In base (n - 2): any number n can be expressed as n = 1 × (n - 2) + 2
  • This gives us the representation 12 in base (n - 2)
  • 12 is not a palindrome
  • Therefore, any n > 4 is not strictly palindromic

Case 3: When n < 4

  • For n = 0, 1, 2, 3, the range of bases to check would be empty or invalid
  • These cases don't satisfy the strictly palindromic condition either

Since every possible value of n fails to be strictly palindromic for at least one base in the required range, the solution is simply:

class Solution:
    def isStrictlyPalindromic(self, n: int) -> bool:
        return False

This constant-time O(1) solution leverages mathematical reasoning to avoid the complex implementation of base conversion and palindrome checking that would normally be required.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through why n = 9 is not strictly palindromic to illustrate the solution approach.

For n = 9, we need to check if it's palindromic in every base from 2 to 7 (which is n - 2).

Base 2: 9 in binary is 1001

  • Is 1001 a palindrome? Yes! ✓

Base 3: 9 in base 3 is 100 (since 9 = 1×9 + 0×3 + 0×1)

  • Is 100 a palindrome? No! ✗ (but let's continue to see the pattern)

Base 4: 9 in base 4 is 21 (since 9 = 2×4 + 1)

  • Is 21 a palindrome? No! ✗

Base 5: 9 in base 5 is 14 (since 9 = 1×5 + 4)

  • Is 14 a palindrome? No! ✗

Base 6: 9 in base 6 is 13 (since 9 = 1×6 + 3)

  • Is 13 a palindrome? No! ✗

Base 7: 9 in base 7 is 12 (since 9 = 1×7 + 2)

  • Is 12 a palindrome? No! ✗

Notice the critical insight: In base 7 (which is n - 2), we get 12. This will always happen for any n > 4 when converting to base (n - 2) because:

  • n = 1 × (n - 2) + 2
  • This mathematically guarantees the representation 12 in base (n - 2)

Since 12 is never a palindrome, and we need ALL bases to produce palindromes, every number fails the strictly palindromic test. This is why the solution can simply return false without doing any actual conversions or palindrome checks.

Solution Implementation

1class Solution:
2    def isStrictlyPalindromic(self, n: int) -> bool:
3        """
4        Determines if a number is strictly palindromic.
5      
6        A number is strictly palindromic if it is a palindrome in every base b
7        where 2 <= b <= n-2.
8      
9        Mathematical proof: For any n >= 4, when converted to base (n-2),
10        n equals "12" in that base (n = 1*(n-2) + 2), which is not a palindrome.
11        Therefore, no number can be strictly palindromic.
12      
13        Args:
14            n: An integer to check for strict palindromicity
15          
16        Returns:
17            bool: Always False, as no number can be strictly palindromic
18        """
19        # No number can satisfy the strictly palindromic condition
20        return False
21
1class Solution {
2    /**
3     * Determines if a number n is strictly palindromic.
4     * A number is strictly palindromic if it is a palindrome in every base b where 2 <= b <= n-2.
5     * 
6     * Mathematical proof: For any n >= 4, when converted to base (n-2), 
7     * n equals 1*(n-2) + 2, which gives the representation "12" in base (n-2).
8     * Since "12" is not a palindrome, no number can be strictly palindromic.
9     * 
10     * @param n the number to check (constraint: 4 <= n <= 10^5)
11     * @return always false, as no number in the valid range is strictly palindromic
12     */
13    public boolean isStrictlyPalindromic(int n) {
14        // No number in the valid input range can be strictly palindromic
15        return false;
16    }
17}
18
1class Solution {
2public:
3    /**
4     * Determines if a number is strictly palindromic.
5     * A number is strictly palindromic if it is a palindrome in every base b 
6     * where 2 <= b <= n-2.
7     * 
8     * Mathematical insight: For any n >= 4, when converted to base (n-2),
9     * n equals "12" in that base, which is not a palindrome.
10     * Therefore, no number can be strictly palindromic.
11     * 
12     * @param n The integer to check (n >= 4)
13     * @return Always returns false as no number is strictly palindromic
14     */
15    bool isStrictlyPalindromic(int n) {
16        // No number can satisfy the strictly palindromic condition
17        return false;
18    }
19};
20
1/**
2 * Checks if a number is strictly palindromic.
3 * A number is strictly palindromic if it is a palindrome in every base from 2 to n-2.
4 * 
5 * Mathematical insight: For any n >= 4, the number n in base (n-2) is always "12",
6 * which is not a palindrome. Therefore, no number >= 4 can be strictly palindromic.
7 * For n < 4, the range [2, n-2] is empty or invalid, so the condition vacuously fails.
8 * 
9 * @param n - The number to check for strict palindromicity
10 * @returns Always returns false as no positive integer is strictly palindromic
11 */
12function isStrictlyPalindromic(n: number): boolean {
13    // No positive integer n can be strictly palindromic
14    // This is because for any n >= 4:
15    // - In base (n-2), n equals "12" (1*(n-2) + 2)
16    // - "12" is not a palindrome
17    // For n < 4, there are no valid bases to check
18    return false;
19}
20

Time and Space Complexity

The time complexity is O(1) because the function performs a single operation - returning a boolean value False. There are no loops, recursive calls, or any operations that depend on the input size n. Regardless of the value of n, the function immediately returns False in constant time.

The space complexity is O(1) because the function uses a fixed amount of memory. It doesn't create any data structures, arrays, or variables that grow with the input size. The function only returns a boolean value without allocating any additional space that scales with n.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Attempting to Implement the Naive Solution

Many developers instinctively start implementing base conversion and palindrome checking logic without first analyzing the mathematical properties of the problem. This leads to unnecessary complex code:

Pitfall Example:

class Solution:
    def isStrictlyPalindromic(self, n: int) -> bool:
        # Unnecessary implementation
        def toBase(num, base):
            if num == 0:
                return "0"
            digits = []
            while num:
                digits.append(str(num % base))
                num //= base
            return ''.join(reversed(digits))
      
        def isPalindrome(s):
            return s == s[::-1]
      
        for base in range(2, n - 1):
            if not isPalindrome(toBase(n, base)):
                return False
        return True

Solution: Before implementing, analyze edge cases mathematically. Testing with small values like n=4 and n=5 reveals the pattern that leads to the constant-time solution.

2. Misunderstanding the Base Range

Developers might incorrectly implement the base range as [2, n-1] or [2, n] instead of [2, n-2].

Pitfall Example:

# Wrong range - includes n-1
for base in range(2, n):  # Should be range(2, n-1)
    # check palindrome

Solution: Carefully read the problem statement. The range is explicitly stated as bases from 2 to n-2 inclusive, which in Python is range(2, n-1).

3. Forgetting Edge Cases in Base Conversion

If implementing base conversion, forgetting to handle special cases like n=0 or single-digit representations can cause errors.

Pitfall Example:

def toBase(num, base):
    digits = []
    while num:  # Fails when num=0
        digits.append(num % base)
        num //= base
    return digits  # Returns empty list for 0

Solution: Even though the final solution is simply return False, understanding proper base conversion helps verify the mathematical proof. Handle zero explicitly and ensure single digits are represented correctly.

4. Over-optimizing Without Understanding

Some might see the return False solution and assume it's a trick question or placeholder code without understanding the mathematical reasoning.

Solution: Document the mathematical proof in comments. The solution is valid because:

  • For n=4: binary representation is "100" (not palindrome)
  • For n>4: base (n-2) representation is always "12" (not palindrome)
  • This proves no number can be strictly palindromic
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which algorithm should you use to find a node that is close to the root of the tree?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More