01: Introduction
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.
02: 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
| Input | Expected Output | Reason |
|---|---|---|
"madam" |
True |
Reads the same both ways |
"hello" |
False |
Reversed is “olleh” |
"racecar" |
True |
Classic palindrome |
"A man a plan a canal Panama" |
True |
After cleaning spaces/case |
"a" |
True |
Single character is always a palindrome |
"" |
True |
Empty string is a palindrome by convention |
03: 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.
04: Flowchart

05: 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.
# 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.
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.
# 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.
# 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
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
06: Dry Run
Let’s trace through the two-pointer method step by step on the input "madam" (length = 5):
True. “madam” is a Palindrome.07: Complete Python Program
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}")
08: 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 |
09: Test Cases
| # | Input | Expected | Category |
|---|---|---|---|
| 1 | "madam" |
True |
Normal palindrome |
| 2 | "hello" |
False |
Normal non-palindrome |
| 3 | "Racecar" |
True |
Mixed case |
| 4 | "A man a plan a canal Panama" |
True |
Spaces included |
| 5 | "Was it a car or a cat I saw?" |
True |
Special characters |
| 6 | "a" |
True |
Single character |
| 7 | "" |
True |
Empty string |
| 8 | "aaaa" |
True |
All same characters |
10: 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 oflen(s) - 1. - Using recursion without base case: Forgetting the
left >= rightbase case leads to infinite recursion. - Not handling empty strings: An empty string is a palindrome by convention — make sure your code handles it.
11: Method Comparison
| Method | Easy to Write | Space Efficient | Interview Preferred | Handles 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 |
12: 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.
13: Common Interview Questions
- Write a function to check if a string is a palindrome without using extra space.
- How would you modify your palindrome check to ignore spaces and special characters?
- Can you check if a number (integer) is a palindrome without converting it to a string?
- What is the time and space complexity of your palindrome check solution?
- Check if any permutation of a string can form a palindrome.
- Find the longest palindromic substring in a given string.
14: 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.
Frequently Asked Questions
s == s[::-1]. To handle uppercase letters, use s.lower() == s.lower()[::-1]. This is the simplest palindrome string check in Python.re.sub(r'[^a-z0-9]', '', s). After cleaning, apply any palindrome check method. The cleaned version “amanaplanacanalpanama” is indeed a palindrome.