#9
Palindrome Number
EasyMathHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Without String Conversion)★ | |
|---|---|---|
| Time | O(n²) | O(log10(n)) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(log10(n))Space O(1)
Instead of converting the integer to a string, we can reverse half of the number and compare it with the other half. This avoids the overhead of string manipulation and works directly with the integer.
⚙️
Algorithm
4 steps- 1Step 1: If x is negative or ends with 0 (and is not 0), return false, as it can't be a palindrome.
- 2Step 2: Initialize a variable to store the reversed half of the number.
- 3Step 3: While x is greater than the reversed half, keep extracting the last digit of x and adding it to the reversed half.
- 4Step 4: After the loop, compare x with the reversed half. If they are equal or if x is equal to reversed half divided by 10 (for odd-length numbers), return true; otherwise, return false.
solution.py14 lines
1# Full working Python code with comments
2
3def is_palindrome(x: int) -> bool:
4 # Step 1: Handle negative numbers and multiples of 10
5 if x < 0 or (x % 10 == 0 and x != 0):
6 return False
7 reversed_half = 0
8 # Step 2: Reverse half of the number
9 while x > reversed_half:
10 reversed_half = reversed_half * 10 + x % 10
11 x //= 10
12 # Step 3: Compare the two halves
13 return x == reversed_half or x == reversed_half // 10
14ℹ
Complexity note: The time complexity is O(log10(n)) because we are effectively reducing the number of digits in x by half with each iteration. The space complexity is O(1) since we are using a constant amount of space.
- 1Recognizing that palindromes read the same forwards and backwards is key. This can be approached through string manipulation or mathematical reversal.
- 2Understanding how to handle edge cases, such as negative numbers and trailing zeros, is crucial for accurate solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.