Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Palindrome Number

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "9" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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?

Explanation

Here's the breakdown of the solution:

  • Handle Negative Numbers and Trailing Zeros: Negative numbers cannot be palindromes (due to the negative sign). Also, numbers ending in 0 (except for 0 itself) cannot be palindromes because the reversed number would have a leading zero.
  • Reverse Half of the Number: We only need to reverse half of the number. We can stop when the reversed number is greater than or equal to the original number.
  • Compare and Account for Odd Length: If the original number is equal to the reversed number, it's a palindrome. If the original number has an odd number of digits, we can divide the reversed number by 10 to remove the middle digit and then compare.

  • Runtime complexity: O(log x) (due to the number of digits in x) & Storage complexity: O(1)

Code

    def isPalindrome(x: int) -> bool:
    """
    Checks if an integer is a palindrome.

    Args:
        x: The integer to check.

    Returns:
        True if x is a palindrome, False otherwise.
    """

    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

More from this blog

C

Chatmagic blog

2894 posts