PythonPython StringsPython palindrome algorithms
How do you check whether a string is a palindrome?
Question 75 of 88 · Updated
On this page
- 1. Check an exact palindrome with slicing
- 2. Two-pointer algorithm
- Why it is correct
- 3. Ignore case, spaces and punctuation when required
- 4. Unicode representation and palindrome semantics
- 5. Constant auxiliary space for ASCII phrase palindromes
- 6. Practical validation: a nonempty palindrome word
- 7. Time and space complexity
- 8. Common mistakes and edge-case tests
- Interview-ready answer
- Official references
A palindrome is a sequence that reads the same forwards and backwards. In Python, the simplest exact string palindrome check is text == text[::-1]. It compares the original string with its reverse. A two-pointer algorithm provides the same exact result without constructing a reversed copy.
Before choosing an algorithm, define the comparison policy: should case, punctuation, whitespace or Unicode representation differences matter? Different policies can legitimately produce different answers.
1. Check an exact palindrome with slicing#
PYTHONdef is_palindrome(text): return text == text[::-1] for text in ['level', 'abba', 'python', '', 'x', 'Level']: print(repr(text), is_palindrome(text))
Output:
'level' True
'abba' True
'python' False
'' True
'x' True
'Level' FalseThe slice with step -1 traverses Unicode code points in reverse order. String equality compares the two sequences. No characters are ignored, so uppercase L and lowercase l are different.
The empty string and every single-code-point string satisfy the mathematical definition: reversing them does not change their sequence. Some applications require a nonempty word, which is an additional validation rule rather than a property of palindrome detection.
The input is assumed to be a str. Without explicit validation, the slicing expression also works on some other sequence types and may raise TypeError on unsupported values.
2. Two-pointer algorithm#
For long strings or an interview that requires constant auxiliary space, compare symmetric positions directly.
PYTHONdef palindrome_two_pointers(text): left, right = 0, len(text) - 1 while left < right: if text[left] != text[right]: return False left += 1 right -= 1 return True print(palindrome_two_pointers('racecar')) print(palindrome_two_pointers('abca'))
Output:
True
FalseThe left pointer starts at the first code point, and the right pointer starts at the last. If the two values differ, the sequence cannot be a palindrome. Otherwise, move both pointers toward the center.
| Iteration for racecar | Left index and value | Right index and value | Result |
|---|---|---|---|
| 1 | 0: r | 6: r | Match |
| 2 | 1: a | 5: a | Match |
| 3 | 2: c | 4: c | Match |
| Stop | 3: e | 3: e | Same center position; no pair remains |
For an even-length string, the pointers cross after comparing the two central positions. For an odd-length string, they meet at the central position. Both cases terminate successfully if every examined pair matches.
Why it is correct#
At the start of each iteration, all symmetric pairs outside the remaining interval have been checked and found equal. This is the loop invariant. The comparison either detects a mismatch and correctly rejects the input, or checks another symmetric pair and shrinks the interval while preserving the invariant.
Once the interval contains at most one code point, no unchecked pair remains. The invariant then implies that all symmetric pairs match. The interval shrinks after each successful comparison, so the algorithm terminates.
There are at most floor(n/2) pair comparisons for an input of length n.
3. Ignore case, spaces and punctuation when required#
A common interview variation asks whether a phrase is a palindrome after ignoring case and all non-alphanumeric characters. Define that rule explicitly rather than silently changing the meaning of the basic check.
PYTHONdef phrase_palindrome(text): cleaned = ''.join(ch for ch in text.casefold() if ch.isalnum()) return cleaned == cleaned[::-1] for text in ['A man, a plan, a canal: Panama!', 'Never odd or even', 'Hello', '!!!']: print(phrase_palindrome(text))
Output:
True
True
False
TrueThe method casefold() applies Unicode default caseless mappings. The filter keeps characters accepted by str.isalnum(), including Unicode letters and numeric characters. The remaining sequence is compared with its reverse.
The last input contains no alphanumeric characters and becomes an empty string. It passes under this exact policy. If at least one retained character is required, add an explicit nonempty check.
The order of transformations is part of the policy. Some Unicode case mappings produce multiple code points, including combining characters. Applying a filter before folding can therefore produce a different result from applying it after folding. This example deliberately folds first and filters second.
The predicate isalnum() is broader than ASCII letter-and-digit validation. Do not reuse this phrase policy for a protocol requiring ASCII-only input.
4. Unicode representation and palindrome semantics#
Python string indexing and slicing operate on Unicode code points, not necessarily user-perceived characters. Visually equivalent text can contain different code-point sequences.
PYTHONfrom unicodedata import normalize text = 'e\u0301xé' print(text == text[::-1]) text = normalize('NFC', text) print(text == text[::-1]) text = 'ßxSS'.casefold() print(text, text == text[::-1])
Output:
False
True
ssxss TrueThe original accented example begins with a decomposed e plus combining acute accent and ends with precomposed é. The exact code-point palindrome check rejects it. NFC normalization makes the first and last accented letters identical in this particular example.
The third case demonstrates why case folding cannot always be implemented by comparing one original code point from each side. The lowercase sharp s folds to two s characters. A comparison of the complete folded sequence can therefore succeed even though the original sequence has different lengths on its two sides.
Normalization, case folding and grapheme segmentation are different operations. NFC is not a general grapheme-cluster segmentation algorithm. A human-facing palindrome checker may require a carefully defined sequence of normalized grapheme clusters, rather than reversing individual code points.
For exact sequence or protocol comparisons, do not normalize or fold unless the contract explicitly requires it. When a caseless policy must also account for canonical equivalence, define an appropriate normalization and folding sequence, as discussed in the earlier case-conversion lesson.
5. Constant auxiliary space for ASCII phrase palindromes#
If the contract explicitly restricts input to ASCII and ignores punctuation and case, the two-pointer algorithm can skip unwanted characters without building an entire cleaned string.
PYTHONdef palindrome_ascii_phrase(text): if not text.isascii(): raise ValueError('ASCII required') left, right = 0, len(text) - 1 while left < right: if not text[left].isalnum(): left += 1 continue if not text[right].isalnum(): right -= 1 continue if text[left].lower() != text[right].lower(): return False left += 1 right -= 1 return True print(palindrome_ascii_phrase('A, b, a!')) print(palindrome_ascii_phrase('abca')) try: palindrome_ascii_phrase('é') except ValueError as exc: print(exc)
Output:
True
False
ASCII requiredEach iteration removes an irrelevant boundary character or compares a pair of relevant characters. Both pointers move monotonically inward, so each position is visited a bounded number of times.
ASCII validation matters here because ASCII letter case conversion maps each individual letter to exactly one code point. The algorithm must not be advertised as a constant-space implementation of the general Unicode casefold-and-filter policy. Unicode mappings can expand, and normalization can change the sequence being compared.
The function assumes a str input and returns True if no relevant characters remain, just like the preceding phrase policy. Other choices for empty input can be implemented as additional contract checks.
6. Practical validation: a nonempty palindrome word#
An API may need to distinguish an invalid argument from an ordinary negative palindrome result.
PYTHONdef valid_palindrome_word(text): if not isinstance(text, str): raise TypeError('expected str') if not text: return False return text == text[::-1] print(valid_palindrome_word('')) print(valid_palindrome_word('noon')) try: valid_palindrome_word(None) except TypeError as exc: print(exc)
Output:
False
True
expected strHere the empty string deliberately returns False and an invalid type raises TypeError. The function checks a nonempty exact palindrome, not whether every character is a letter. Despite its name, it would accept an exact palindrome containing punctuation or digits. If a lexical word is required, validate the permitted alphabet separately.
The caller should determine whether invalid input should raise an exception, return a structured validation error or be handled by a higher-level interface. Do not silently convert None or arbitrary objects to strings.
7. Time and space complexity#
For ordinary CPython strings, assume constant-time indexed access to a code point and a bounded-width internal Unicode representation.
| Approach | Worst-case time | Auxiliary storage | Important condition |
|---|---|---|---|
| Reverse slice and compare | O(n) | O(n) | Materializes reversed text |
| Exact two pointers | O(n) | O(1) | No full reversed copy |
| Casefold, filter and reverse | O(n + m) | O(n + m) | m is the size of transformed text; fixed Unicode version has bounded casefold expansion |
| ASCII phrase two pointers | O(n) | O(1) | ASCII-only contract |
| Recursive symmetric comparison | O(n) for index-based recursion | O(n) call stack | Recursive slicing can introduce extra copying |
The two-pointer algorithm can return immediately on a mismatch. The slicing approach generally constructs the reverse before performing the comparison, so it usually does work proportional to the input length even if the first pair differs.
These are asymptotic models, not benchmark results. CPython implements slicing and comparison in optimized native code, whereas a Python-level loop has interpreter overhead. The slicing version can be faster for many ordinary inputs despite requiring more auxiliary storage. Benchmark representative text sizes if runtime performance is a deciding factor.
A recursive approach is unnecessary for this problem. Repeatedly slicing text inside recursion can cause quadratic cumulative copying and can exceed the recursion limit on large inputs.
8. Common mistakes and edge-case tests#
| Mistake | Correct approach |
|---|---|
| Comparing the string with sorted(text) | Compare against the reverse, not sorted order |
| Using text.reverse() | str has no in-place reverse method; use slicing or two pointers |
| Forgetting to move both pointers | Shrink the remaining interval after each matching pair |
| Assuming empty input must fail | Define a nonempty requirement explicitly if needed |
| Assuming lower() handles all caseless equivalences | Use the intended Unicode case-folding policy |
| Comparing individual folded characters for arbitrary Unicode | Account for expansions and normalization of the full sequence |
| Assuming visual characters equal code points | Define a grapheme-aware policy when necessary |
A useful test suite includes odd and even lengths, a mismatch at an outer pair, a mismatch near the center, an empty string, a single character, mixed case, punctuation-only input, and composed/decomposed Unicode examples.
The randomized tests for this lesson compare the exact two-pointer function with the reverse-slice implementation and compare the ASCII phrase algorithm with the materialized casefold-and-filter implementation. Agreement provides evidence that these alternative implementations follow the same policies for the tested inputs.
Interview-ready answer#
A palindrome reads identically forwards and backwards under a specified comparison policy. In Python, the concise exact check is text == text[::-1], which takes O(n) time and generally O(n) additional storage. For O(1) auxiliary space, initialize pointers at both ends, compare symmetric characters, move inward after each match, and return False immediately on a mismatch. If case and punctuation should be ignored, explicitly define a normalization/filtering policy. Unicode case folding can expand characters, so an ASCII-specific two-pointer shortcut is not automatically equivalent to full Unicode normalization and comparison.
Official references#
- Python Standard Library — Common Sequence Operations
- Python Standard Library — Text Sequence Type: str
- Python Standard Library — str.casefold
- Python Standard Library — str.isalnum
- Python Standard Library — str.isascii
- Python Standard Library — unicodedata.normalize
- Python Unicode HOWTO
Verification note: Six runnable example groups, including two caught exceptions, matched their expected outputs on CPython 3.13.5. A seeded suite of 500 iterations executed 1,000 randomized equivalence assertions: 500 exact palindrome comparisons and 500 ASCII phrase palindrome comparisons. Two triple-backtick fenced Mermaid flowcharts were manually reviewed; the local Mermaid CLI was unavailable, so parser-level validation and live website rendering were not performed. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.Common Sequence Operationsdocs.python.org
- 2.unicodedata.normalizedocs.python.org
- 3.Python Unicode HOWTOdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design