Palindrome Number – Solution & Complexity

Solution Walkthrough

  1. Step 1: Handle Impossible Cases First

    • Negative numbers are not palindromes because the minus sign appears only on the left.
    • Positive numbers ending in 0 cannot be palindromes unless the number itself is 0.
    • These checks avoid extra work and prevent misleading reversals.
    if x < 0 or (x % 10 == 0 and x != 0):
        return False
  2. Step 2: Reverse Only Half of the Number

    • Reversing the whole number works, but reversing half avoids unnecessary work and possible overflow in some languages.
    • Repeatedly move the last digit of x into reversed_half.
    • Stop when reversed_half is greater than or equal to the remaining x.
    reversed_half = 0
    while x > reversed_half:
        reversed_half = reversed_half * 10 + x % 10
        x //= 10
  3. Step 3: Compare Even and Odd Lengths

    • For an even number of digits, the remaining left half should equal the reversed right half.
    • For an odd number of digits, the middle digit is irrelevant.
    • Dropping the middle digit with reversed_half // 10 handles odd lengths.
    return x == reversed_half or x == reversed_half // 10
  4. Step 4: Final Complete Solution

    • The algorithm uses arithmetic only, so it satisfies the no-string follow-up.
    • It processes about half the digits of the input.
    • Time complexity is O(log10 n), and extra space complexity is O(1).
    def is_palindrome_number(x: int) -> bool:
        if x < 0 or (x % 10 == 0 and x != 0):
            return False
    
        reversed_half = 0
        while x > reversed_half:
            reversed_half = reversed_half * 10 + x % 10
            x //= 10
    
        return x == reversed_half or x == reversed_half // 10

FAQ