Palindrome Number - Problem
Check if a Number Reads the Same Forwards and Backwards

A palindrome is a sequence that reads the same forwards and backwards - like the word "racecar" or the number 12321. Your task is to determine if a given integer x is a palindromic number.

Goal: Return true if the integer is a palindrome, false otherwise.

Examples:
121true (reads as 121 backwards)
-123false (negative numbers aren't palindromes)
10false (reads as 01 backwards, which is just 1)

Challenge: Can you solve this without converting the number to a string?

Input & Output

example_1.py — Python
$ Input: x = 121
Output: true
💡 Note: 121 reads as 121 from left to right and right to left, so it's a palindrome
example_2.py — Python
$ Input: x = -121
Output: false
💡 Note: From left to right it reads -121, but from right to left it becomes 121-, which is not the same
example_3.py — Python
$ Input: x = 10
Output: false
💡 Note: Reads 10 from left to right but 01 from right to left, which equals 1, so it's not a palindrome

Visualization

Tap to expand
Palindrome Detection: Mathematical ApproachOriginal Number12321Step 1x = 12321reversed = 0Extract: 1Step 2x = 1232reversed = 1Extract: 2Step 3x = 123reversed = 12Extract: 3Finalx = 12reversed = 123Stop: x ≤ revPalindrome CheckCompare: x == reversed // 1012 == 123 // 10 = 12 ✓Result: TRUE
Understanding the Visualization
1
Handle Edge Cases
Negative numbers and multiples of 10 (except 0) cannot be palindromes
2
Start Reversal Process
Initialize reversed_half = 0 and begin extracting digits from right
3
Extract and Build
Take last digit of x, add to reversed_half, remove from x
4
Continue Until Halfway
Stop when x ≤ reversed_half (we've processed half the digits)
5
Compare Results
Check if x equals reversed_half (even digits) or reversed_half/10 (odd digits)
Key Takeaway
🎯 Key Insight: We only need to reverse half the digits mathematically, avoiding string conversion and achieving optimal O(1) space complexity!

Time & Space Complexity

Time Complexity
⏱️
O(log n)

We process half the digits of the number, which is still O(log n) where n is the input

n
2n
Linearithmic
Space Complexity
O(1)

Only uses a constant amount of extra space for variables

n
2n
Linear Space

Constraints

  • -231 ≤ x ≤ 231 - 1
  • Follow-up: Can you solve it without converting the integer to a string?
Asked in
Meta 45 Amazon 38 Google 32 Microsoft 28 Apple 22
58.5K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen