LeetCode 9 Solution: Palindrome Number Explained in Python

L

In this blog post, we’ll dive into the LeetCode 9 solution for the Palindrome Number problem. If you’re preparing for coding interviews or looking to level up your problem-solving skills, this problem is a fantastic way to practice working with numbers in Python without resorting to string manipulation. Let’s explore the logic and code to solve this popular problem efficiently.

Problem Statement

The task in the LeetCode 9 problem is simple: given an integer x, determine whether it is a palindrome. A number is considered a palindrome if it reads the same both forward and backward. For example, 121 is a palindrome because reading it from left to right and right to left gives the same result.

You might think of solving this problem by converting the number to a string, reversing it, and checking if the reversed version matches the original. However, the challenge here is to solve the problem without converting the integer into a string.

Breaking Down the Problem: Understanding Palindromes

Before jumping into the LeetCode 9 solution, let’s understand the nature of palindromes a bit better. For a number to be a palindrome, its digits must mirror symmetrically. That means for a number like 12321, the first digit should match the last digit, the second should match the second-to-last, and so on.

For negative numbers, there’s no need to check further. They can never be palindromes because the negative sign - isn’t mirrored. Similarly, numbers like 10 aren’t palindromes since reversing them would produce 01, which isn’t the same.

Key Insights for a Mathematical Approach

Given that converting the integer to a string is off-limits, we need a clever mathematical trick to solve the problem efficiently. Instead of reversing the entire number, we can reverse only half of the digits. This way, we can compare the original first half of the number with the reversed second half. If both halves match, the number is a palindrome.

One important thing to keep in mind is handling numbers with odd digits. In such cases, the middle digit can be ignored because it will always be the same when read from both directions.

Writing the LeetCode 9 Solution in Python

Let’s look at the Python code that solves the problem. Our approach focuses on reversing half of the number and comparing it with the remaining half.

def isPalindrome(x: int) -> bool:
    # Early return for negative numbers and numbers ending with 0
    if x < 0 or (x % 10 == 0 and x != 0):
        return False

    reversed_half = 0
    while x > reversed_half:
        # Reverse the last digit and reduce x
        reversed_half = reversed_half * 10 + x % 10
        x //= 10

    # Check if either both halves are the same or, in case of odd digits, ignoring the middle one
    return x == reversed_half or x == reversed_half // 10

This code snippet may look concise, but it packs a punch in terms of efficiency and clarity. The logic behind the solution is straightforward: we reverse the digits of the number step by step using basic arithmetic operations like modulus and division. Once we’ve reversed half of the number, we compare it with the other half.

If the reversed half matches the remaining half of x, we can confidently say that the number is a palindrome. For odd-digit numbers, we ignore the middle digit by dividing the reversed number by 10.

Edge Cases to Consider

As with any coding problem, it’s essential to handle edge cases to ensure the solution works in all scenarios. For the LeetCode 9 solution, the most critical edge cases are:

  • Negative numbers: Any negative number (like -121) will return False since the negative sign makes it impossible to be a palindrome.
  • Numbers ending in zero: Any number ending in zero (like 10) is not a palindrome unless the number itself is 0. This is because reversing a number like 10 gives 01, which doesn’t match the original.
  • Single-digit numbers: Any single-digit number, from 0 to 9, is always a palindrome because it reads the same backward and forward.

Time and Space Complexity Analysis

The time complexity of this approach is O(log₁₀(n)), where n is the given number x. This is because we are processing half of the digits of the number, and the number of digits in a number n is proportional to the logarithm base 10 of n.

As for space complexity, our solution is O(1). We only use a few variables (x, reversed_half) to store the current state of the number and its reverse, meaning that our space usage does not grow with the size of the input.

Why This Solution Works for LeetCode 9

The reason this mathematical approach works so well for the LeetCode 9 problem is that it avoids the pitfalls of converting an integer to a string, which can increase time and space complexity. By focusing on reversing only half of the number, we reduce unnecessary operations and ensure that the solution remains both time and space efficient. This is crucial when dealing with the upper limits of the problem’s constraints, where x can be as large as 2^31 - 1.

Additionally, the solution is easy to extend to similar problems that involve palindromes or number manipulations, making it a useful technique to have in your coding toolkit.

LeetCode 9 Solution: Summary

In this blog, we’ve explored an efficient and clean LeetCode 9 solution to the Palindrome Number problem using Python. Instead of relying on string conversion, we developed a mathematical approach that reverses half of the number and compares it with the other half. This ensures the solution is optimal in both time and space complexity.

With edge cases properly handled and the solution carefully tailored to the problem constraints, you now have a robust method for solving this problem in a coding interview or practice session.

Would you like to explore more variations of palindrome problems or see how this solution can be extended further? Feel free to leave a comment or ask for more insights! Happy coding!

Happy Coding!


Looking for more LeetCode solutions? Stay tuned for upcoming guides on tackling other LeetCode challenges in Python. Whether you’re preparing for technical interviews or aiming to improve your coding skills, exploring a variety of problems will enhance your understanding and proficiency.

You can find this problem on LeedCode, click here.

Add comment

By Peter

About me

Hi, I’m Peter, a professional developer with over 25 years of experience. My journey with coding started when I was just a kid, exploring the world of programming and building my first projects out of pure curiosity and passion. Since then, I’ve turned this lifelong passion into a rewarding career, working on a wide range of projects, from small scripts to complex applications.

Now, I’m here to help others get started with coding through this blog. I know that learning to code can feel overwhelming at first, but I believe that with the right guidance, anyone can develop the skills they need to become a proficient programmer. My goal is to simplify the learning process and provide step-by-step resources that make coding accessible, fun, and practical for everyone.

Whether you’re just starting out or looking to sharpen your skills, I hope this blog serves as a valuable resource on your coding journey. Let’s dive into Python together!

Get in touch

Have any questions or feedback? Feel free to reach out—I’m always happy to help you on your coding journey!

Tags