Leetcode 2396: Strictly Palindromic Number

grid47
grid47
Exploring patterns and algorithms
Mar 12, 2024 4 min read

An integer n is considered strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the representation of n in base b is a palindrome. A number is palindromic in a base if the string representation of that number in that base reads the same forward and backward. Your task is to determine if the given integer n is strictly palindromic or not.
Problem
Approach
Steps
Complexity
Input: The input consists of a single integer `n` (4 <= n <= 10^5), where `n` is the number you need to check for strict palindromicity across various bases.
Example: n = 5
Constraints:
• 4 <= n <= 10^5
Output: Return `true` if `n` is strictly palindromic, otherwise return `false`.
Example: Output: false
Constraints:
Goal: The goal is to check if for all bases between 2 and `n - 2`, the base `b` representation of `n` is palindromic. If for any base it is not palindromic, return false.
Steps:
• 1. Iterate through all bases from 2 to `n - 2`.
• 2. For each base, convert `n` to its string representation in that base.
• 3. Check if the string representation is a palindrome.
• 4. If a non-palindromic representation is found, return false.
• 5. If all representations are palindromic, return true.
Goal: The solution must work within the time limits for large values of `n`, and correctly handle the representation of `n` in bases ranging from 2 to `n-2`.
Steps:
• Ensure the solution can handle values of `n` up to 10^5 efficiently.
Assumptions:
• The number `n` is always greater than or equal to 4.
Input: n = 6
Explanation: In base 2: 6 = 110 (not palindromic), base 3: 6 = 20 (not palindromic), base 4: 6 = 12 (not palindromic), hence 6 is not strictly palindromic.

Input: n = 7
Explanation: In base 2: 7 = 111 (palindromic), base 3: 7 = 21 (not palindromic), hence 7 is not strictly palindromic.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus