LeetCode 2396: Strictly Palindromic Number

LeetCode 2396 Solution 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.

LeetCode 2396 Solutions in Java, C++, Python

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;
    }
}

Interactive Code Editor for LeetCode 2396

Improve Your LeetCode 2396 Solution

Use the editor below to refine the provided solution for LeetCode 2396. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems