DEV Community

Piyush Acharya
Piyush Acharya

Posted on

2396. LeetCode's Strictly Palindromic Number - FASTEST JAVA SOLUTION - 0 MS RUNTIME ⏩⏩

Intuition

The code seems to be checking if a given number is strictly palindromic in all bases from 2 to n-2.

Approach

The code seems to be checking if a given number is strictly palindromic in all bases from 2 to n-2.

Complexity

  • Time complexity: The time complexity of the convert method is O(log n), since it is converting the number to a different base. The time complexity of the isPalindrome method is O(log n), since it is checking if the number is a palindrome. The time complexity of the isStrictlyPalindromic method is O(n log n), since it is iterating through all bases from 2 to n-2, and for each base it is calling the convert and isPalindrome methods. Therefore, the overall time complexity is O(n log n).
  • Space complexity: The space complexity of the convert method is O(log n), since it is creating a string representation of the number in a different base. The space complexity of the isPalindrome method is O(log n), since it is creating a string representation of the number. The space complexity of the isStrictlyPalindromic method is O(1), since it is only using a constant amount of space. Therefore, the overall space complexity is O(log n).

Code

class Solution {
    public boolean isStrictlyPalindromic(int n) {
        int size = n - 2;
        for (int i = 2; i <= size; i++) {
            if (!isPalindrome(convert(n, i))) {
                return false;
            }
        }
        return true;
    }

    public long convert(int number, int base) {
        String binary = Integer.toString(number, base);
        return Long.parseLong(binary);
    }

    public Boolean isPalindrome(long number) {
        String num = Long.toString(number);
        int max = num.length() / 2;
        for (int i = 0; i < max; i++) {
            if (!(num.charAt(i) == num.charAt(num.length() - i - 1))) {
                return false;
            }
        }
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)