Palindrome Number - Problem

Given an integer x, return true if x is a palindrome, and false otherwise.

A palindrome number reads the same forward and backward. For example, 121 is a palindrome while 123 is not.

Follow up: Could you solve it without converting the integer to a string?

Input & Output

Example 1 — Positive Palindrome
$ Input: x = 121
Output: true
💡 Note: 121 reads the same from left to right and right to left
Example 2 — Not a Palindrome
$ Input: x = -121
Output: false
💡 Note: From left to right it reads -121, but from right to left it becomes 121- which is different
Example 3 — Single Digit
$ Input: x = 7
Output: true
💡 Note: Single digit numbers are always palindromes

Constraints

  • -231 ≤ x ≤ 231 - 1

Visualization

Tap to expand
Palindrome Number - Half Reversal Approach INPUT Integer x = 121 1 2 1 pos 0 pos 1 pos 2 Read Forward: 121 Read Backward: 121 x = 121 (3 digits) ALGORITHM STEPS 1 Check Negative x >= 0? Yes, continue 2 Reverse Half Build reversed from end x=121, rev=0 x=12, rev=1 (121%10) x=1, rev=12 (rev*10+2) Stop: x(1) <= rev(12) Final: x=1, rev=12 3 Compare Halves x == rev OR x == rev/10 4 Check Match 1 == 12/10? 1==1 Yes! O(log n) time, O(1) space FINAL RESULT Palindrome Check: 1 2 1 Mirror Line (middle digit) First half = Reversed second half x(1) == rev/10(12/10=1) Output: true 121 is a Palindrome OK Key Insight: Instead of reversing the entire number, we only reverse HALF of it. For odd-length numbers, we compare x with reversed/10 to skip the middle digit. This avoids integer overflow and uses O(1) space since we don't need to store the number as a string or array. TutorialsPoint - Palindrome Number | Half Reversal (Optimal) Approach
Asked in
Amazon 15 Microsoft 12 Google 8 Apple 6
329.6K Views
High Frequency
~15 min Avg. Time
8.5K 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