Taro Logo

Palindrome Number

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+22
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.4K views
Topics:
Bit Manipulation

Given an integer x, return true if x is a palindrome, and false otherwise.

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:

  • -231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of the integer `x`, and should we expect 32-bit signed integer limits (e.g., `-2^31` to `2^31 - 1`)?
  2. How should negative numbers be handled? For example, does `-121` count as a palindrome since it reads as `121-` backward?
  3. Can we solve this by converting the integer to a string, or is there a constraint against using extra space (i.e., should we solve it mathematically by reversing the integer)?
  4. How should trailing zeros be handled? For example, is `10` considered a palindrome?
  5. What should be returned for single-digit numbers?

Brute Force Solution

Approach

To check if a number reads the same forwards and backwards using the brute force approach, we can convert the number into text form and look at it from both directions at once. By systematically comparing the characters from opposite ends, we can determine if they match completely.

Here's how the algorithm would work step-by-step:

  1. Take the given number and write it down as a sequence of characters on a piece of paper.
  2. Point at the very first character on the left and the very last character on the right.
  3. Compare the two characters you are pointing at to see if they are the exact same symbol.
  4. If they match, move your left finger one step to the right and your right finger one step to the left.
  5. Repeat this comparison process for the new pair of characters.
  6. Keep doing this until your fingers meet in the middle or cross paths.
  7. If every single pair you checked matched successfully, then the number is a palindrome.
  8. If you ever find a pair that does not match, immediately stop because the number is not a palindrome.

Code Implementation

def is_palindrome(input_number):
    # Convert the number to text so we can easily access characters from both ends
    string_representation = str(input_number)
    
    left_pointer = 0
    right_pointer = len(string_representation) - 1
    
    # Compare characters inward until our pointers meet or cross each other
    while left_pointer < right_pointer:
        if string_representation[left_pointer] != string_representation[right_pointer]:
            # Immediate failure means we stop early because it is not a palindrome
            return False
        
        left_pointer += 1
        right_pointer -= 1
        
    # Reaching this point means all character pairs matched successfully
    return True

Big(O) Analysis

Time Complexity
O(n) – In this approach, the input integer is first converted into a string of length n, where n represents the number of digits in the integer. We then use a two-pointer technique to compare characters from the outer edges inward until the pointers meet in the middle. Since each of the n digits is visited and compared at most once, the total number of operations scales linearly with the number of digits. This results in roughly n/2 comparisons, which simplifies to a Big O time complexity of O(n).
Space Complexity
O(N) – The brute force approach relies on converting the input number into a sequence of characters, such as a string, to allow indexed comparisons from both ends. Letting N represent the number of digits in the given integer, this string requires allocating auxiliary memory proportional to the length of the number. The two pointers used to traverse the string from opposite ends only consume a constant amount of extra memory for index tracking. Therefore, the total extra memory scales directly with the number of digits, resulting in a linear space complexity of O(N).

Optimal Solution

Approach

To determine if a number reads the same forwards and backwards, the most efficient strategy is to take the second half of the number and flip it around. By comparing this flipped version to the first half, we can instantly tell if the number is a palindrome without having to process every single digit.

Here's how the algorithm would work step-by-step:

  1. First, check for any obvious non-palindromes, such as negative numbers, because a minus sign at the front means it can never match the back.
  2. Also check if the number ends in zero (except for zero itself), because no palindrome can start with a zero.
  3. Begin peeling off digits from the right end of the original number one by one.
  4. As you peel each digit, build up a mirrored version by shifting previous digits over and adding the new one.
  5. Keep doing this until you have successfully moved half of the digits over to your mirrored version.
  6. At this halfway point, compare the first half of the original number with your newly built mirrored version.
  7. If they match completely, you have a palindrome; if they do not match, it is not a palindrome.

Code Implementation

def is_palindrome(candidate_number):
    # Negative numbers and numbers ending in zero cannot be palindromes except zero itself.
    if candidate_number < 0 or (candidate_number % 10 == 0 and candidate_number != 0):
        return False

    mirrored_version = 0

    # We peel digits until the original number is less than or equal to the mirrored half.
    while candidate_number > mirrored_version:
        last_digit = candidate_number % 10
        mirrored_version = (mirrored_version * 10) + last_digit
        candidate_number = candidate_number // 10

    # Check for both even and odd length numbers by comparing halves.
    return candidate_number == mirrored_version or candidate_number == mirrored_version // 10

Big(O) Analysis

Time Complexity
O(log10(n)) – The algorithm processes the input integer by peeling off its digits one by one from the right until reaching the halfway point. Since the number of digits in an integer n is proportional to the base-10 logarithm log10(n), the loop runs roughly half that many times. Consequently, the total operations scale with the number of digits, approximating (log10(n)) / 2 steps, which simplifies in Big O notation to O(log10(n)).
Space Complexity
O(1) – The algorithm relies entirely on a fixed number of scalar variables, such as integers used to track the reversed half and the remaining digits of the input. No extra data structures like arrays, lists, or hash maps are created, and no recursion is utilized. Therefore, the auxiliary memory remains completely constant regardless of how large the input number N is, resulting in a space complexity of O(1).

Edge Cases

Negative integers
How to Handle:
Return false immediately because the negative sign at the front prevents it from ever matching the reversed number.
Single-digit numbers from zero to nine
How to Handle:
Return true automatically since single-digit numbers always read the same forwards and backwards.
Numbers ending with zero except zero itself
How to Handle:
Return false because no non-zero integer can start with a zero when reversed.
Even-length palindromes like 1221
How to Handle:
Compare the original left half with the fully reversed right half after half the iterations.
Odd-length palindromes like 12321
How to Handle:
Compare the left half with the right half after removing the middle digit by integer division by ten.
Maximum and minimum boundary integer values
How to Handle:
Reversing only half of the digits completely avoids potential integer overflow issues.
Numbers with all identical digits like 1111
How to Handle:
Symmetric numeric construction naturally treats these as valid palindromes.
Zero input
How to Handle:
Return true because zero is symmetrical and fits the base palindrome definition.
0/75 completed