Strictly Palindromic Number - Problem

An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic.

Given an integer n, return true if n is strictly palindromic and false otherwise.

A string is palindromic if it reads the same forward and backward.

Input & Output

Example 1 — Small Number
$ Input: n = 9
Output: false
💡 Note: In base 2: 9 = 1001 (palindromic), but in base 3: 9 = 100 (not palindromic), so return false
Example 2 — Very Small Number
$ Input: n = 4
Output: false
💡 Note: Need to check bases [2]. In base 2: 4 = 100 (not palindromic), so return false
Example 3 — Edge Case
$ Input: n = 2
Output: false
💡 Note: No bases to check (range [2, 0] is empty), but by definition return false

Constraints

  • 1 ≤ n ≤ 2 × 109

Visualization

Tap to expand
Strictly Palindromic Number INPUT n = 9 Definition: Check if n is palindrome in ALL bases from 2 to n-2 (inclusive) Base Range for n=9: b = 2, 3, 4, 5, 6, 7 6 bases to check (n-2 = 7, so 2 to 7) ALGORITHM STEPS 1 Base 2: 9 = 1001 1001 is palindrome? YES 2 Base 3: 9 = 100 100 is palindrome? NO All Base Conversions: Base Value Palin? 2 1001 YES 3 100 NO 4 21 NO 5 14 NO 6 13 NO 7 12 NO 3 Found non-palindrome Stop and return false 4 Optimal: return false For n > 4, always false! FINAL RESULT false Explanation: 9 in base 3 = "100" "100" reversed = "001" "100" != "001" 100 != 001 NOT Strictly Palindromic Failed at base 3 Key Insight: No number n > 4 is strictly palindromic! For any n > 4, the representation in base (n-2) is always "11", which IS a palindrome, BUT the representation in base (n-3) is never a palindrome. Therefore, the optimal solution is simply: return false; (O(1) time complexity). This is a mathematical trick question! TutorialsPoint - Strictly Palindromic Number | Optimal Solution
Asked in
Google 15 Meta 8 Amazon 12
15.0K Views
Low Frequency
~5 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen