9. Palindrome Number - Explanation
Description
You are given an integer x, return true if x is a palindrome, and false otherwise.
Note: An integer is a palindrome when it reads the same forward and backward.
For example, 111 and 121 are palindromes while 123 is not.
Example 1:
Input: x = 1
Output: trueExample 2:
Input: x = -1
Output: falseConstraints:
-(2^31) <= x <= ((2^31) - 1)
Follow up: Could you solve it without converting the integer to a string?
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- String Manipulation - Converting integers to strings and comparing characters
- Math Operations (Modulo/Division) - Extracting and removing digits from integers
- Two Pointers - Comparing elements from both ends of a sequence
1. Convert to String
Intuition
The most straightforward approach is to convert the integer to a string and check if the string is a palindrome by reversing it.
If the original string equals its reversed version, the number is a palindrome.
Algorithm
- Convert the integer to its string representation.
- Reverse the string.
- Compare the original string with the reversed string.
- Return
trueif they are equal,falseotherwise.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the number of digits in the given integer.
2. Convert to String (Optimal)
Intuition
Instead of creating a reversed copy of the entire string, we can compare characters from both ends moving toward the center. This avoids the extra space needed for the reversed string.
We only need to check half the string since we compare characters in pairs.
Algorithm
- Convert the integer to its string representation.
- Initialize two pointers:
iat the start andjat the end. - While
i < n/2, compares[i]withs[n - i - 1]. If they differ, returnfalse. - Return
trueif all comparisons pass.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the number of digits in the given integer.
3. Reverse the Integer
Intuition
Without using string conversion, we can reverse the entire integer mathematically and compare it to the original. If they are equal, the number is a palindrome.
Negative numbers cannot be palindromes because of the negative sign. We build the reversed number digit by digit using modulo and division operations.
Algorithm
- If the number is negative, return
falseimmediately. - Initialize
rev = 0andnum = x. - While
num > 0:- Extract the last digit using
num % 10. - Append it to
revby computingrev = rev * 10 + digit. - Remove the last digit from
numusing integer division.
- Extract the last digit using
- Compare
revwith the originalxand returntrueif equal.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the number of digits in the given integer.
4. Two Pointers
Intuition
We can compare digits from both ends without converting to a string or reversing the entire number. The idea is to extract the leftmost and rightmost digits and compare them.
We use a divisor to extract the leftmost digit and modulo to extract the rightmost digit, then shrink the number from both ends.
Algorithm
- If the number is negative, return
false. - Find the divisor
divsuch thatx / divgives the first digit. This is the largest power of 10 less than or equal tox. - While
x > 0:- Compare the first digit (
x / div) with the last digit (x % 10). If they differ, returnfalse. - Remove both the first and last digits:
x = (x % div) / 10. - Update the divisor:
div /= 100(since we removed two digits).
- Compare the first digit (
- Return
trueif all comparisons pass.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the number of digits in the given integer.
5. Reverse Half of the Number
Intuition
Reversing the entire number risks integer overflow. A clever optimization is to reverse only the second half of the number and compare it to the first half.
We keep extracting digits from the end and building the reversed half until the reversed half is greater than or equal to the remaining number. At that point, we have processed half (or just past half) of the digits.
Algorithm
- Handle edge cases: negative numbers and numbers ending in
0(except0itself) are not palindromes. - Initialize
rev = 0. - While
x > rev:- Extract the last digit of
xand append it torev. - Remove the last digit from
x.
- Extract the last digit of
- After the loop, compare
x == rev(even length) orx == rev / 10(odd length, where the middle digit is inrev). - Return
trueif either condition holds.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the number of digits in the given integer.
Common Pitfalls
Forgetting Negative Numbers Are Not Palindromes
Negative numbers have a minus sign at the front, so they can never be palindromes (e.g., -121 reads as 121- backwards). Failing to handle negative numbers as an early return case leads to incorrect results or issues with modulo operations on negative values.
Not Handling Numbers Ending in Zero
Numbers ending in zero (except zero itself) cannot be palindromes because leading zeros are not allowed in integers. For example, 10 would need to be 01 reversed, which is not a valid representation. The half-reversal approach fails on these cases without explicit handling, as the loop condition x > rev may never be satisfied correctly.
Sign in to join the discussion