String Algorithms · Python · DSA

Check if String is Palindrome
in Python – 3 Easy Methods

📅 Published 2025 ⏱ 10 min read 🏷 Arrays · Strings · Interview Prep
⚡ Featured Snippet

A palindrome string reads the same forward and backward, like "madam" or "racecar". To check if a string is a palindrome in Python, compare it with its reverse using s == s[::-1], or use a two-pointer approach for O(1) space efficiency.

Introduction

You have probably heard the word palindrome before — words like madam, racecar, level, and civic are all palindromes. They read the same whether you go left to right or right to left. But how do you actually check if a string is a palindrome in Python using code?

This is one of the most common string problems asked in coding interviews at companies like Amazon, Google, and Infosys. It looks simple on the surface, but interviewers specifically look for how you handle edge cases — things like uppercase letters, spaces, and special characters.

Real-world examples: "racecar" → reads the same both ways ✅  |  "hello" → does not ❌

In this guide, you will learn the palindrome algorithm using three different Python methods — from the simplest one-liner to the most interview-friendly two-pointer technique. Every method is explained with full code, dry run, and complexity analysis.

Problem Statement

Given a string, determine whether it reads the same forward and backward.

Return True if it is a palindrome, False otherwise.

Input / Output Format

InputExpected OutputReason
"madam"TrueReads the same both ways
"hello"FalseReversed is "olleh"
"racecar"TrueClassic palindrome
"A man a plan a canal Panama"TrueAfter cleaning spaces/case
"a"TrueSingle character is always a palindrome
""TrueEmpty string is a palindrome by convention

Why This Problem Matters

String Manipulation

Teaches indexing, slicing, and reversal — core Python skills.

Two Pointer Pattern

The two-pointer technique used here applies to dozens of other problems.

Interview Frequency

Appears in beginner rounds at Amazon, TCS, Wipro, Infosys, and more.

Edge Case Thinking

Trains you to think about case sensitivity, spaces, and special characters.

Key Intuition — Symmetry

A palindrome is essentially a mirror image of itself. The character at position 0 must match position n-1, position 1 must match position n-2, and so on. If any pair does not match, the string is not a palindrome.

Think of it like folding the string in half. If the left side and right side align perfectly — it's a palindrome.

Palindrome Visualization

Let's see how the two-pointer approach works on "madam" step by step:

▶ Two-Pointer Visualization — "madam"
m
a
d
a
m

Step-by-step pointer movement:

L=0 → 'm' ✓ Match 'm' ← R=4
L=1 → 'a' ✓ Match 'a' ← R=3
L=2 → 'd' ✓ Centre R=2

All pointers matched → "madam" is a Palindrome ✓

Flowchart

START
Read input string s
Clean: lowercase + remove non-alphanumeric
Set left = 0, right = len(s) - 1
left < right?
s[left] == s[right]?
YES → left++, right--
Move pointers inward
Return True — Palindrome
END
Note: If s[left] ≠ s[right] at any point, immediately return False.

Pseudocode

Pseudocode
FUNCTION isPalindrome(s):
    clean_s = lowercase(s) + remove non-alphanumeric chars

    left  = 0
    right = length(clean_s) - 1

    WHILE left < right:
        IF clean_s[left] != clean_s[right]:
            RETURN False
        left  = left + 1
        right = right - 1

    RETURN True

Method 1 — Reverse String (Simplest)

The most direct way to check a palindrome is to reverse the string and compare it to the original. Python makes this extremely easy with slice notation.

Python — Method 1: Reverse
# Method 1: Reverse the string and compare
def is_palindrome_reverse(s):
    # Convert to lowercase to handle case insensitivity
    s = s.lower()
    return s == s[::-1]

# Test
print(is_palindrome_reverse("madam"))    # True
print(is_palindrome_reverse("hello"))    # False
print(is_palindrome_reverse("Racecar"))  # True

How it works:

  • s.lower() converts everything to lowercase so "Madam" and "madam" are treated the same.
  • s[::-1] creates a reversed copy of the string using Python's slice syntax.
  • If the original and reversed string are equal, it's a palindrome.
Drawback: This creates an extra reversed copy of the string, using O(n) extra space.

Method 2 — Two Pointer Approach (Interview Preferred)

This is the method interviewers want to see. Instead of creating a reversed string, we use two pointers — one starting from the left, one from the right — and move them inward, comparing characters at each step.

Python — Method 2: Two Pointer
# Method 2: Two Pointer — O(n) time, O(1) space
def is_palindrome_two_pointer(s):
    s = s.lower()
    left, right = 0, len(s) - 1

    while left < right:
        if s[left] != s[right]:
            return False
        left  += 1
        right -= 1

    return True

# Test
print(is_palindrome_two_pointer("racecar"))  # True
print(is_palindrome_two_pointer("hello"))    # False
print(is_palindrome_two_pointer("level"))    # True

Why this is better:

  • No extra string is created — space complexity is O(1).
  • Early exit — if a mismatch is found, we return immediately without checking the rest.
  • Shows pattern recognition skill — interviewers love this approach.

Method 3 — Recursion (Advanced)

You can also solve this recursively. The idea is simple: check if the first and last characters match, then recursively check the middle part.

Python — Method 3: Recursion
# Method 3: Recursion
def is_palindrome_recursive(s, left=0, right=None):
    if right is None:
        s     = s.lower()
        right = len(s) - 1

    if left >= right:          # Base case
        return True
    if s[left] != s[right]:    # Mismatch
        return False
    return is_palindrome_recursive(s, left+1, right-1)

print(is_palindrome_recursive("madam"))   # True
print(is_palindrome_recursive("python"))  # False
Note: Recursion adds O(n) call stack space and risks RecursionError for very long strings. Prefer the two-pointer method in interviews.

⚠️ Critical Edge Cases

❗ Case Sensitivity

The string "Madam" should return True, but without converting to lowercase, 'M' != 'm' will cause it to fail. Always call .lower() first.

❗ Spaces and Special Characters

The phrase "A man a plan a canal Panama" is a famous palindrome — but only after you remove spaces and punctuation. Here is how to handle it:

Python — Cleaned String Version
import re

def is_palindrome_clean(s):
    # Keep only alphanumeric characters, convert to lowercase
    cleaned = re.sub(r'[^a-z0-9]', '', s.lower())
    return cleaned == cleaned[::-1]

print(is_palindrome_clean("A man a plan a canal Panama"))  # True
print(is_palindrome_clean("Was it a car or a cat I saw?"))  # True
print(is_palindrome_clean("race a car"))                   # False

❗ Empty String and Single Character

Python — Edge Case Tests
print(is_palindrome_reverse(""))    # True  — empty string
print(is_palindrome_reverse("a"))   # True  — single character
print(is_palindrome_reverse("aa"))  # True  — two same chars
print(is_palindrome_reverse("ab"))  # False — two different chars

Dry Run — "madam"

Let's trace through the two-pointer method step by step on the input "madam" (length = 5):

Dry Run Trace
Step
Left
Right
Comparison
Result
1
0 → 'm'
4 → 'm'
'm' == 'm'
✓ OK
2
1 → 'a'
3 → 'a'
'a' == 'a'
✓ OK
3
2 → 'd'
2 → 'd'
left ≥ right
◉ Done
All pairs matched → Return True. "madam" is a Palindrome.

Complete Python Program

Python — Full Program with Input Handling
import re

# ── Method 1: Reverse ────────────────────────────
def palindrome_reverse(s):
    s = s.lower()
    return s == s[::-1]

# ── Method 2: Two Pointer (Space Efficient) ───────
def palindrome_two_pointer(s):
    s = s.lower()
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1; right -= 1
    return True

# ── Cleaned Version (handles spaces & symbols) ────
def palindrome_clean(s):
    cleaned = re.sub(r'[^a-z0-9]', '', s.lower())
    return cleaned == cleaned[::-1]

# ── Driver Code ───────────────────────────────────
test_cases = [
    ("madam", True),
    ("hello", False),
    ("Racecar", True),
    ("A man a plan a canal Panama", True),
    ("a", True),
    ("", True),
]

print(f"{'String':35} {'Reverse':10} {'2-Ptr':10} {'Clean'}")
print("-" * 65)
for s, expected in test_cases:
    r1 = palindrome_reverse(s)
    r2 = palindrome_two_pointer(s)
    r3 = palindrome_clean(s)
    print(f"{s!r:35} {str(r1):10} {str(r2):10} {r3}")

Time & Space Complexity

Method Time Complexity Space Complexity Notes
Reverse String O(n) O(n) Creates a reversed copy
Two Pointer O(n) O(1) No extra string — best for interviews
Recursion O(n) O(n) Call stack uses O(n) space
Cleaned String O(n) O(n) Handles real-world strings

Test Cases

#InputExpectedCategory
1"madam"TrueNormal palindrome
2"hello"FalseNormal non-palindrome
3"Racecar"TrueMixed case
4"A man a plan a canal Panama"TrueSpaces included
5"Was it a car or a cat I saw?"TrueSpecial characters
6"a"TrueSingle character
7""TrueEmpty string
8"aaaa"TrueAll same characters

Mistakes Beginners Make

  • Ignoring case: Treating "Madam" as non-palindrome because 'M' ≠ 'm'. Always use .lower().
  • Not cleaning spaces: "race car" fails unless spaces are removed.
  • Wrong index handling: Off-by-one errors when setting right = len(s) instead of len(s) - 1.
  • Using recursion without base case: Forgetting the left >= right base case leads to infinite recursion.
  • Not handling empty strings: An empty string is a palindrome by convention — make sure your code handles it.

Method Comparison

MethodEasy to WriteSpace EfficientInterview PreferredHandles Edge Cases
Reverse String Yes No Acceptable Partial
Two Pointer Medium Yes Best Partial
Recursion Hard No Bonus Partial
Cleaned String Yes No Recommended Full

Real-World Applications

Data Validation

VINs, product codes, and IDs sometimes use palindrome checks for integrity verification.

DNA Sequence Analysis

In bioinformatics, palindromic DNA sequences indicate restriction enzyme binding sites.

Cryptography

Some cipher design patterns use palindromic structures for symmetric encryption.

Natural Language Processing

Detecting palindromes in text processing pipelines and word games.

Common Interview Questions

  1. Write a function to check if a string is a palindrome without using extra space.
  2. How would you modify your palindrome check to ignore spaces and special characters?
  3. Can you check if a number (integer) is a palindrome without converting it to a string?
  4. What is the time and space complexity of your palindrome check solution?
  5. Check if any permutation of a string can form a palindrome.
  6. Find the longest palindromic substring in a given string.

Conclusion

Checking if a string is a palindrome in Python is one of those problems that looks simple but tests your understanding of string manipulation, edge cases, and algorithm design. Here is a quick recap:

  • Method 1 (Reverse): Simple one-liner — good for beginners and quick solutions.
  • Method 2 (Two Pointer): Space-efficient and interview-preferred — learn this one well.
  • Method 3 (Recursion): Good to know as a bonus — but not ideal for production.
  • Always clean the string before checking — handle case, spaces, and special characters.
Pro tip for interviews: Start with the reverse method to show you know Python, then mention the two-pointer approach for optimized space. Handle edge cases out loud — it impresses interviewers.

Frequently Asked Questions

A palindrome string is a string that reads the same forward and backward. For example, "madam", "racecar", and "level" are palindromes. An empty string and single-character strings are also considered palindromes.
You can check if a string is a palindrome in Python with: s == s[::-1]. To handle uppercase letters, use s.lower() == s.lower()[::-1]. This is the simplest palindrome string check in Python.
Yes. By convention, an empty string is considered a palindrome. When you compare "" with its reverse "", they are equal, so the condition returns True. Most interview problems follow this convention.
The two-pointer method uses O(1) extra space because it doesn't create a reversed copy of the string. It also has early termination — as soon as a mismatch is found, it returns False without processing the rest of the string. This makes it more efficient in practice.
First, convert the string to lowercase. Then remove all non-alphanumeric characters using re.sub(r'[^a-z0-9]', '', s). After cleaning, apply any palindrome check method. The cleaned version "amanaplanacanalpanama" is indeed a palindrome.
All three methods — reverse, two-pointer, and recursion — have O(n) time complexity where n is the length of the string. However, the two-pointer method has O(1) space complexity, while reverse and recursion both require O(n) extra space.
Yes, absolutely. Any single character like "a", "1", or "z" is trivially a palindrome because there is nothing to compare — it reads the same in both directions. All palindrome check algorithms will correctly return True for single-character strings.

Tags

palindrome string python check if string is palindrome two pointer palindrome palindrome algorithm string palindrome check reverse string python palindrome interview question case insensitive palindrome DSA python python string problems