Palindrome Number Problem Explained

Palindrome Number Problem Explained

A palindrome number is a number that reads the same whether you look at it from left to right or right to left. Take 121, for example. Flip it around and you still get 121. The same goes for 1221, 9009, or even a single digit like 7. Numbers like these have a kind of numerical symmetry that makes them interesting both in mathematics and in computer science.

In math, palindrome numbers show up in some genuinely fascinating places. There is even a subset called palindromic primes, where a number is both prime and a palindrome, like 11, 101, or 131. These are studied in recreational mathematics and number theory. Outside of academic math, palindrome number patterns are used in checksum algorithms, error detection in data transmission, and coding puzzles that test your understanding of digit manipulation.

In coding interviews, the palindrome number problem is a staple for a reason. It looks simple on the surface but forces you to think carefully about edge cases, number properties, and trade-offs between time and space. If you are preparing for FAANG or similar company interviews, problems involving digit manipulation and number properties are common, and this one is a great place to start.

Key Takeaways

  • A palindrome number reads the same both ways at the digit level; single-digit numbers always qualify, negatives never do.
  • Trailing zeros are a trap; any positive number ending in zero cannot be a palindrome because reversing it would produce a leading zero.
  • All three solutions are O(d) time, but only the half-reversal and digit-comparison approaches achieve O(1) space, making them the efficient choices.
  • Half-reversal is the safest interview answer; reversing only half the digits eliminates any risk of integer overflow on large inputs.
  • This problem tests judgment, not just code; interviewers care about edge case awareness, space-time trade-off reasoning, and digit-level thinking, not just whether you got the right output.

Check If the Number Is a Palindrome: Problem Statement

Given an integer, determine whether it is a palindrome. Return true if it is, and false if it is not.

Input: An integer num
Output: true (or 1) if num is a palindrome, false (or 0) if it is notConstraints:
-2^31 <= num <= 2^31 – 1Note: Negative integers are never palindromes because the minus sign does not
mirror correctly when the number is reversed.

Examples

Input Output Explanation
1234321 true (1) Reversed: 1234321. Same as input, so it is a palindrome
-1223 false (0) Reversed: 3221-. Negative numbers are never palindromes
121 true (1) Reversed: 121. Reads the same both ways
10 false (0) Reversed: 01 = 1. Not equal to 10, so not a palindrome
0 true (1) A single zero reads the same in both directions
1001 true (1) Reversed: 1001. Symmetrical, so it is a palindrome

Also Read: Frequently Asked FAANG DSA Interview Questions You Should Know in 2026

Understanding Palindrome Numbers

Before jumping into code, it helps to understand what makes a number a palindrome at the digit level. When you reverse the digits of a number and get back the same number, it is a palindrome. This is the same idea behind palindrome strings like ‘racecar’ or ‘madam’, just applied to integers.

Here is a simple table showing a few numbers, their reverses, and whether they qualify:

Number Reversed Palindrome?
121 121 Yes
1221 1221 Yes
12321 12321 Yes
123 321 No
-121 121- No, because it is a negative number
10 01 No, (leading zero)
7 7 Yes (single digit)

One thing worth noting: a number ending in zero (other than zero itself) can never be a palindrome. For the reversed number to match the original, the first digit would have to be zero, which is not possible in standard integer representation. This is an important edge case that any solid solution needs to handle.

As a fun aside, some palindrome numbers are also prime numbers, making them palindromic primes. Examples include 11, 101, 131, and 313. These sit at the intersection of number theory and combinatorics and are a popular topic in math olympiad problems. For our purposes, though, we are just checking the palindrome property, not whether the number is prime.

Approach Overview

There are three solid ways to solve this problem, each with its own trade-offs. We will walk through all three, so you understand not just how to solve it but why each approach works and when you might prefer one over another.

  • Solution 1: Convert the integer to a string, then check if the string is a palindrome. Simple and intuitive, but it uses extra space.
  • Solution 2: Extract the second half of the number as an integer, reverse it, and compare with the first half. Uses O(1) extra space.
  • Optimized Solution: Access individual digits mathematically without converting or reversing anything. Also, O(1) space, and a great demonstration of digit-level thinking.

All three approaches run in O(d) time, where d is the number of digits in the input. The main difference is in space usage and elegance. In a real interview setting, any of these would be acceptable, but examiners at top companies tend to appreciate the second or third approach since they avoid the string conversion overhead.

Solution 1: Convert to String

How It Works

The simplest approach is to convert the number into a string and then check whether that string reads the same forwards and backwards. To do this, we extract digits one at a time from the right side of the number using modulo and integer division, building the string character by character.

Once we have the string, we compare the first character with the last, the second with the second-to-last, and so on, up to the midpoint. If all pairs match, the number is a palindrome.

Step-by-Step

  • If num is negative, return false immediately.
  • Extract each digit from right to left using num % 10, add it to the string, then divide num by 10.
  • Once all digits are extracted, iterate from index 0 to len/2 and compare str[i] with str[len – i – 1].
  • If any pair mismatches, return false. Otherwise, return true.

Code

/*
 * Time: O(d)  |  Auxiliary Space: O(d)  |  Total Space: O(d)
 * d = number of digits in num
 */
bool is_palindrome(int num) {
    if (num < 0) {
        return false;
    }
    string str = "";
    int digit;
    while (num > 0) {
        digit = num % 10;
        str += ('0' + digit);
        num /= 10;
    }
    int len = str.length();
    for (int i = 0; i < len / 2; ++i) {
        if (str[i] != str[len - i - 1]) {
            return false;
        }
    }
    return true;
}
💡 Pro Tip: When we build the string by extracting digits from the right, we are actually storing the reverse of the number. But since palindromes are symmetric, checking whether the reverse is a palindrome is exactly the same as checking the original.

Solution 2: Extract the Second Half

How It Works

This approach avoids the string entirely. Instead of reversing the whole number, we only reverse the second half and compare it to the first half. This sidesteps any potential integer overflow issues that would occur if we reversed a very large number like 1999999999.

We repeatedly extract the rightmost digit from num and build a new integer called sec_half. We stop when sec_half is greater than or equal to num. At that point, num holds the first half and sec_half holds the reversed second half.

For even-digit numbers, num should equal sec_half. For odd-digit numbers, we can discard the middle digit by checking num == sec_half / 10.

Step-by-Step

  • If num is 0, return true.
  • If num is negative or ends in zero (and is not zero itself), return false.
  • Repeatedly extract the last digit of num and append it to sec_half, while removing that digit from num.
  • Stop when num <= sec_half.
  • Check num == sec_half (even digits) or num == sec_half / 10 (odd digits).

Code

/*
 * Time: O(d)  |  Auxiliary Space: O(1)  |  Total Space: O(1)
 */
bool is_palindrome(int num) {
    if (num == 0) {
        return true;
    }
    if (num < 0 || num % 10 == 0) {
        return false;
    }
    int sec_half = 0;
    int digit;
    while (num > sec_half) {
        digit    = num % 10;
        sec_half = sec_half * 10 + digit;
        num      /= 10;
    }
    return (num == sec_half || num == sec_half / 10);
}

A tricky edge case here is a number like 1100. If we follow the algorithm naively, we eventually get num = 1 and sec_half = 1 (since trailing zeros collapse). The early check for num % 10 == 0 prevents this from incorrectly returning true.

Optimized Solution: Check Without Reversing

How It Works

This is the most mathematically elegant approach. Instead of reversing anything, we directly access digits at any position using arithmetic. For a number with d digits, the i-th digit from the left is: (num / 10^(d – i)) % 10.

Using this formula, we compare the first digit with the last, the second with the second-to-last, and so on until we reach the middle. No string, no reversal, no extra space.

Step-by-Step

  • Handle the edge case for negative numbers and zero.
  • Calculate d = log10(num) + 1 to find the number of digits.
  • Set div1 = 10^(d-1) to extract leftmost digits and div2 = 1 to extract rightmost digits.
  • For each pair from outside in, check (num / div1) % 10 == (num / div2) % 10.
  • Move div1 inward by dividing by 10 and div2 inward by multiplying by 10.
  • If all pairs match, return true.

Code

/*
 * Time: O(d)  |  Auxiliary Space: O(1)  |  Total Space: O(1)
 */
bool is_palindrome(int num) {
    if (num < 0) {
        return false;
    }
    if (num == 0) {
        return true;
    }
    int num_of_digits = log10(num) + 1;
    int div1          = pow(10, num_of_digits - 1);
    int div2          = 1;
    for (int i = 0; i < num_of_digits / 2; i++) {
        if ((num / div1) % 10 != (num / div2) % 10) {
            return false;
        }
        div1 /= 10;
        div2 *= 10;
    }
    return true;
}

Edge Cases

Edge cases are where many candidates slip up in interviews, even if they nail the general logic. Here are the key ones to watch for with the palindrome number problem:

  • Negative numbers: -121 reversed is ‘121-‘, which is not the same. All negative numbers return false. This is the first check in every solution.
  • Numbers ending in zero: A number like 100 reversed would start with 0, which is not a valid integer. So 100 is not a palindrome. Any positive number whose last digit is zero (except zero itself) is automatically not a palindrome.
  • Single-digit numbers: Any number from 0 to 9 is a palindrome by definition since there is nothing to reverse and compare.
  • Zero: Zero is a palindrome. It reads the same both ways.
  • Large numbers: Numbers near the 32-bit integer limit can cause overflow if you try to reverse the entire number as an integer. Solution 2 avoids this by only reversing half the digits.

Time and Space Complexity

All three approaches run in O(d) time, where d is the number of digits. But they differ in how much memory they use:

Approach Time Complexity Space Complexity
Solution 1: Convert to String O(d) O(d) – stores a string of d chars
Solution 2: Extract Second Half O(d) O(1) – only a few integer variables
Optimized: Check Without Reversing O(d) O(1) – only a few integer variables

For most practical purposes and interview settings, Solutions 2 and 3 are preferred because they use constant auxiliary space.

Visual Explanation

Here is a step-by-step illustration of how Solution 2 works on the number 1221:

Step num sec_half Action
Start 1221 0 Initialize sec_half = 0
Step 1 122 1 Extract last digit (1), sec_half = 0*10 + 1 = 1
Step 2 12 12 Extract last digit (2), sec_half = 1*10 + 2 = 12
Stop 12 12 num <= sec_half, so we stop
Check 12 == 12 Match! Even digits: num == sec_half, return true

Now let’s trace the same approach on 12321 (odd number of digits):

Step num sec_half Action
Start 12321 0 Initialize sec_half = 0
Step 1 1232 1 Extract last digit (1), sec_half = 1
Step 2 123 12 Extract last digit (2), sec_half = 12
Step 3 12 123 Extract last digit (3), sec_half = 123
Stop 12 123 num <= sec_half, so we stop
Check 123 == 123/10 = 12 Match! Odd digits: num == sec_half/10, return true

For the optimized solution (Solution 3), think of it like two pointers moving inward. We start from both ends of the number and march toward the center, comparing one digit at a time:

Number:  1  2  3  2  1
         ^           ^   Compare 1 and 1 → Match
            ^      ^     Compare 2 and 2 → Match
               ^          Middle digit (odd length), skip

Result: Palindrome!

Common Mistakes

Here are some of the most common errors people make when implementing this problem:

  • Forgetting to handle negative numbers: Not checking for negatives upfront will cause wrong answers on inputs like -121.
  • Not handling numbers ending in zero: Forgetting the num % 10 == 0 check (for non-zero numbers) leads to incorrect results on inputs like 1100.
  • Integer overflow when reversing the full number: Reversing a number like 1999999999 produces a value that does not fit in a 32-bit integer. Only reversing half the number (Solution 2) avoids this.
  • Off-by-one in the loop: When using the two-pointer digit comparison approach, make sure you iterate to num_of_digits / 2 and not beyond, or you will double-check the middle digit.
  • Treating zero incorrectly: Zero is a valid palindrome. Make sure your early return conditions do not exclude it.
  • Confusing the output type: Some implementations return 0/1 instead of true/false. Know what your function signature expects.

Related Problems

Once you are comfortable with the palindrome number problem, here are some closely related problems worth practicing:

  • Palindrome String: Check whether a given string is a palindrome. A natural extension of this problem to character arrays.
  • Palindrome Linked List: Determine if a singly linked list is a palindrome. This one requires you to reverse part of the list and adds pointer manipulation to the mix.
  • Valid Palindrome: Given a string, consider only alphanumeric characters and ignore cases, then check if it is a palindrome.
  • Palindrome Partitioning: Partition a string such that every substring of the partition is a palindrome.

Working through these in sequence builds a strong intuition for symmetry-based problems, which show up regularly in technical interviews.

Also Read: Palindromic Decomposition Of A String Problem

Practice More Coding Problems

The palindrome number problem is a great starting point, but real interview preparation means consistent practice across a range of problem types. Some areas worth focusing on alongside palindromes include:

  • Two-pointer problems (they share the same inside-out comparison logic)
  • Digit manipulation problems (divisors, modulo, digit extraction)
  • String reversal and comparison problems
  • Dynamic programming on strings and arrays

Conclusion

The palindrome number problem is one of those problems that rewards careful thinking over raw coding speed. The core idea is simple: a number is a palindrome if it reads the same forward and backwards. But getting there efficiently, handling all the edge cases, and being able to explain your trade-offs is what makes the difference in an interview.

Of the three approaches covered here, the half-reversal method (Solution 2) is the most commonly preferred in interviews. It runs in O(d) time with O(1) space and neatly avoids overflow issues that come with reversing the full number. The no-reversal approach (Solution 3) is equally good and shows a strong grasp of digit mathematics, which is always a plus.

Make sure you can explain why negative numbers and numbers ending in zero are automatically excluded, and practice tracing through the algorithm on a few examples by hand before your next interview. That combination of conceptual clarity and practiced execution is what gets offers at top companies.

FAQs: Palindrome Number

Q1. Is 0 a palindrome number?

Explains why zero is a palindrome and why most implementations need a special case for it.

Q2. Are negative numbers ever palindromes?

Clarifies why the minus sign breaks symmetry and why the answer is always false.

Q3. What is the difference between a palindrome string and a palindrome number?

Highlights the key technical difference in how you access elements in each.

Q4. Can you solve the palindrome number problem without converting to a string?

Walks through both non-string approaches and why they are preferred in interviews.

References

  1. Palindromic Number
  2. Palindrome Number

Recommended Reads:

Try yourself in the Editor

Note: Input and Output will already be taken care of.

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Learn to build AI agents to automate your repetitive workflows

Upskill yourself with AI and Machine learning skills

Prepare for the toughest interviews with FAANG+ mentorship

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

Webinar Slot Blocked

Loading_icon
Loading...
*Invalid Phone Number
By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Registration completed!

See you there!

Webinar on Friday, 18th April | 6 PM
Webinar details have been sent to your email
Mornings, 8-10 AM
Our Program Advisor will call you at this time