Palindrome Program in Python (Number and String)
Check whether a number or a string reads the same forwards and backwards.
- Time
O(d) for a number with d digits, O(n) for a string of length n - Space
O(1) for the loop and two-pointer versions, O(n) for slicing - Hints3
- Read2 min
A palindrome reads the same in both directions, like 121 or "madam". In Python, the shortest check for a string is s == s[::-1]. For a number, reverse it with a while loop using % 10 and // 10, then compare with the original. Without slicing, compare characters from both ends with two pointers.
Problem statement
Write a palindrome program in Python that checks:
- a number, for example 121 is a palindrome and 123 is not, and
- a string, for example "madam" is a palindrome and "python" is not.
Show one method with slicing and one without, since teachers and interviewers often ask for the version without slicing.
A non-negative integer n, or a string s.
True if it is a palindrome, otherwise False.
Examples
n = 121True121 reversed is 121.
s = "python"False"python" reversed is "nohtyp".
s = "Never odd or even"TrueAfter removing spaces and making it lowercase, it becomes "neveroddoreven", which is a palindrome.
Constraints
- 0 <= n <= 10^18 for the number check
- The string can be empty or have any characters
Think before you code
Reveal the questions to ask yourself first
- How do you get the last digit of a number? How do you remove it?
- For a string, which character must match
s[0]? - When can you stop comparing?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Palindrome number in Python
Build the reverse digit by digit: rev = rev * 10 + n % 10, then n = n // 10.
Keep a copy of the original, because the loop changes n. Compare at the end.
Palindrome string in Python
| Method | Code | Extra space |
|---|---|---|
| Slicing | s == s[::-1] |
O(n), makes a reversed copy |
| Two pointers | compare s[left] and s[right] |
O(1) |
| Convert number to string | str(n) == str(n)[::-1] |
O(d) |
Two pointers can stop at the first mismatch, so for long strings that are not palindromes it often finishes early.
To reverse a string by hand, see reverse a string in Python.
Dry run
Walk through the example step by step
Number n = 121. original = 121, rev = 0.
n | digit = n % 10 | rev = rev * 10 + digit | n // 10
----+----------------+------------------------+--------
121 | 1 | 1 | 12
12 | 2 | 12 | 1
1 | 1 | 121 | 0
rev == original, so 121 is a palindrome.
String "level" with two pointers:
left | right | s[left] | s[right] | match
-----+-------+---------+----------+------
0 | 4 | l | l | yes
1 | 3 | e | e | yes
2 | 2 | stop, left is not less than right
Solution
Reveal the full Python solution
def is_palindrome_number(n):
if n < 0:
return False
original = n
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 + digit
n = n // 10
return rev == original
def is_palindrome_string(s):
return s == s[::-1]
def is_palindrome_loop(s):
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
for n in [121, 123, 1001]:
print(n, "->", is_palindrome_number(n))
for s in ["madam", "level", "python"]:
print(s, "->", is_palindrome_string(s), is_palindrome_loop(s))Output:
121 -> True
123 -> False
1001 -> True
madam -> True True
level -> True True
python -> False False
is_palindrome_numberuses only arithmetic, so it works without converting to a string.is_palindrome_stringuses slicing. It is the usual answer when slicing is allowed.is_palindrome_loopis the palindrome in Python without slicing. It compares the first and last characters and moves inwards.
Check palindrome in Python for a sentence
Real sentences have spaces, capitals and punctuation. Clean the text first.
text = "Never odd or even"
clean = ""
for ch in text.lower():
if ch.isalnum():
clean += ch
print(clean)
print(clean == clean[::-1])
neveroddoreven
True
Palindrome number in Python with str()
If the question allows strings, this one line also works:
n = 12321
print(str(n) == str(n)[::-1])
True
The same logic in Java is on check whether a number is a palindrome and check whether a string is a palindrome. For more Python interview practice, see the Python interview questions.
O(d) for a number with d digits, O(n) for a string of length nO(1) for the loop and two-pointer versions, O(n) for slicingReview before the interview
Common mistakes
- Using n / 10 instead of n // 10. In Python 3, / gives a float and the loop goes wrong.
- Comparing rev with n after the loop. By then n is 0, so keep a copy of the original first.
- Forgetting that "Madam" and "madam" are different strings. Call lower() if case should not matter.
- Running the two-pointer loop while left <= right. It still works, but the middle character is compared with itself.
Edge cases to test
- n = 0: the loop does not run, rev stays 0, and 0 is a palindrome.
- Numbers ending in 0, like 10 or 120, are never palindromes (except 0 itself).
- Empty string and single character: both are palindromes.
- Negative numbers: -121 is treated as not a palindrome because of the minus sign.
Interview follow-ups
- How would you check a palindrome using recursion?
- Can you check a number palindrome by reversing only half of its digits?
- How would you find the longest palindromic substring in a string?
Keep practising
Check Whether a Number Is a Palindrome
Hints · Dry run · SolutionSolve Similar problemCheck Whether a String Is a Palindrome
Hints · Dry run · SolutionSolve Similar problemCheck Whether a Sentence Is a Palindrome Ignoring Spaces and Case
Hints · Dry run · SolutionSolve Related learningWhat Is Python Used For
TutorialLearn Related learningLoops In Programming
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
