LeetCode 2396: Strictly Palindromic Number Solution

Master LeetCode problem 2396 (Strictly Palindromic Number), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2396. Strictly Palindromic Number

Problem Explanation

Explanation:

To solve this problem, we need to check if a given number n is strictly palindromic. A number is strictly palindromic if, for every base b between 2 and n - 2 inclusive, the string representation of n in base b is palindromic.

We can iterate over the bases from 2 to n - 2 and convert the number n to each base to check if it is a palindrome in that base. If we find a base where n is not a palindrome, we can immediately return false. If we successfully iterate over all bases without finding any base where n is not a palindrome, we return true.

Algorithm:

  1. Iterate over bases from 2 to n - 2.
  2. Convert number n to the current base.
  3. Check if the converted number is a palindrome.
  4. If any base conversion is not a palindrome, return false. Otherwise, return true.

Time Complexity: The time complexity of this algorithm is O(log2(n) * n) since we iterate over each base from 2 to n - 2 and convert the number n to each base.

Space Complexity: The space complexity is O(log2(n)) to store the string representation of the number in different bases.

Solution Code

class Solution {
    public boolean isStrictlyPalindromic(int n) {
        for (int base = 2; base <= n - 2; base++) {
            String numInBase = Integer.toString(n, base);
            if (!isPalindrome(numInBase)) {
                return false;
            }
        }
        return true;
    }
    
    private boolean isPalindrome(String s) {
        int left = 0, right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2396 (Strictly Palindromic Number)?

This page provides optimized solutions for LeetCode problem 2396 (Strictly Palindromic Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2396 (Strictly Palindromic Number)?

The time complexity for LeetCode 2396 (Strictly Palindromic Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2396 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2396 in Java, C++, or Python.

Back to LeetCode Solutions