Beginner String Problems Python

Palindrome Program in Python (Number and String)

Check whether a number or a string reads the same forwards and backwards.

  • TimeO(d) for a number with d digits, O(n) for a string of length n
  • SpaceO(1) for the loop and two-pointer versions, O(n) for slicing
  • Hints3
  • Read2 min
Quick answer

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.

String slicingWhile loopTwo pointersInteger division
1

Problem statement

Write a palindrome program in Python that checks:

  1. a number, for example 121 is a palindrome and 123 is not, and
  2. 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.

Input

A non-negative integer n, or a string s.

Output

True if it is a palindrome, otherwise False.

Examples

Example 1
Inputn = 121
OutputTrue

121 reversed is 121.

Example 2
Inputs = "python"
OutputFalse

"python" reversed is "nohtyp".

Example 3
Inputs = "Never odd or even"
OutputTrue

After 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
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
n % 10 gives the last digit. n // 10 removes it. Use //, not /, which gives a float.
2 Hint 2
s[::-1] is s read from the end to the start.
3 Hint 3
For two pointers, start left at 0 and right at len(s) - 1, and stop when they meet.
4

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.

5

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
6

Solution

Reveal the full Python solution
solution.py
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_number uses only arithmetic, so it works without converting to a string.
  • is_palindrome_string uses slicing. It is the usual answer when slicing is allowed.
  • is_palindrome_loop is 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.

TimeO(d) for a number with d digits, O(n) for a string of length n
SpaceO(1) for the loop and two-pointer versions, O(n) for slicing
7

Review 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

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us