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
Goal: Return
Examples:
•
•
•
Challenge: Can you solve this without converting the number to a string?
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:
•
121 → true (reads as 121 backwards)•
-123 → false (negative numbers aren't palindromes)•
10 → false (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
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
⚡ Linearithmic
Space Complexity
O(1)
Only uses a constant amount of extra space for variables
✓ Linear Space
Constraints
- -231 ≤ x ≤ 231 - 1
- Follow-up: Can you solve it without converting the integer to a string?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code