Practice · 02 Sorted Arrays: Two Pointers · 1/5
Valid Palindrome
Check if a string reads the same from both ends.
Understand the problem
A word-puzzle app shows sentences like "Taco cat!" and asks: does it read the same backwards? You're meant to ignore capitals, spaces and punctuation, so "Taco cat!" counts, because "tacocat" backwards is "tacocat".
A phrase is a palindrome if, after converting all uppercase letters to lowercase and removing all characters that aren't letters or digits, it reads the same forward and backward. Given a string
s, returntrueif it is a palindrome, orfalseotherwise.
| Input | Cleaned | Output |
|---|---|---|
"A man, a plan, a canal: Panama" | amanaplanacanalpanama | true |
"race a car" | raceacar | false |
" " | (empty) | true: an empty string reads the same both ways |
The limits on LeetCode: up to 200,000 printable ASCII characters.
Brute force first
Build the cleaned string, reverse it and compare.
bool isPalindromeCopy(const string& s) {
string cleaned; // a new string: O(n) extra space
for (unsigned char ch : s)
if (isalnum(ch)) cleaned += tolower(ch);
return cleaned == string(cleaned.rbegin(), cleaned.rend()); // and a reversed copy
}static boolean isPalindromeCopy(String s) {
StringBuilder cleaned = new StringBuilder(); // a new string: O(n) extra space
for (char ch : s.toCharArray())
if (Character.isLetterOrDigit(ch)) cleaned.append(Character.toLowerCase(ch));
String forward = cleaned.toString();
return forward.equals(cleaned.reverse().toString()); // and a reversed copy
}def is_palindrome_copy(s):
cleaned = [ch.lower() for ch in s if ch.isalnum()] # a new list: O(n) extra space
return cleaned == cleaned[::-1] # and a reversed copyfunction isPalindromeCopy(s) {
const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, ""); // a new string: O(n) extra space
return cleaned === [...cleaned].reverse().join(""); // and a reversed copy
}func isPalindromeCopy(s string) bool {
var cleaned []byte // a new slice: O(n) extra space
for i := 0; i < len(s); i++ {
if isAlnum(s[i]) {
cleaned = append(cleaned, lower(s[i]))
}
}
for i, j := 0, len(cleaned)-1; i < j; i, j = i+1, j-1 {
if cleaned[i] != cleaned[j] {
return false
}
}
return true
}static bool IsPalindromeCopy(string s)
{
var cleaned = new string(s.Where(char.IsLetterOrDigit).Select(char.ToLower).ToArray()); // O(n) extra
return cleaned == new string(cleaned.Reverse().ToArray()); // reversed copy
}This is already O(n) time, so it's not slow. Its cost is memory: a cleaned copy and a reversed copy, O(n) extra space. For 200,000 characters that's fine on LeetCode, but an interviewer will ask: can you do it without the copies?
See it in a diagram
A palindrome's first letter must equal its last, its second must equal its second-to-last, and so on. So compare from both ends at once, right inside the original string, skipping anything that isn't a letter or digit.
Spot the pattern
Opposite-end two pointers: lo starts at 0, hi at the end, and they move inward until they meet. Each step either skips a character or settles one pair, so the loop runs at most n times and needs only two integers of memory.
The signal: you need to compare the front and back of a sequence together (palindromes, reversing in place, pairs from both ends of sorted data). The next four problems use the same two pointers, with different rules for which one moves.
The optimal solution
lo = 0,hi = len(s) - 1.- While
lo < hi:- if
s[lo]isn't a letter or digit, moveloright; - else if
s[hi]isn't, movehileft; - else if their lowercase forms differ, return
false; - else move both inward.
- if
- Return
true.
Code in 6 languages
Each program runs the three examples from the top.
#include <cctype>
#include <cstdio>
#include <string>
using namespace std;
bool isPalindrome(const string& s) {
int lo = 0, hi = (int)s.size() - 1;
while (lo < hi) {
unsigned char a = s[lo], b = s[hi]; // unsigned: safe for isalnum
if (!isalnum(a)) lo++; // skip spaces and punctuation
else if (!isalnum(b)) hi--;
else if (tolower(a) != tolower(b)) return false; // mismatch: not a palindrome
else { lo++; hi--; } // match: both pointers move in
}
return true;
}
int main() {
const char* tests[] = {"A man, a plan, a canal: Panama", "race a car", " "};
for (const char* s : tests)
printf("\"%s\" -> %s\n", s, isPalindrome(s) ? "true" : "false");
}public class Main {
static boolean isPalindrome(String s) {
int lo = 0, hi = s.length() - 1;
while (lo < hi) {
char a = s.charAt(lo), b = s.charAt(hi);
if (!Character.isLetterOrDigit(a)) lo++; // skip spaces and punctuation
else if (!Character.isLetterOrDigit(b)) hi--;
else if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false; // mismatch
else { lo++; hi--; } // match: both pointers move in
}
return true;
}
public static void main(String[] args) {
String[] tests = {"A man, a plan, a canal: Panama", "race a car", " "};
for (String s : tests)
System.out.println("\"" + s + "\" -> " + isPalindrome(s));
}
}def is_palindrome(s):
lo, hi = 0, len(s) - 1
while lo < hi:
if not s[lo].isalnum():
lo += 1 # skip spaces and punctuation
elif not s[hi].isalnum():
hi -= 1
elif s[lo].lower() != s[hi].lower():
return False # mismatch: not a palindrome
else:
lo += 1 # match: both pointers move in
hi -= 1
return True
tests = ["A man, a plan, a canal: Panama", "race a car", " "]
for s in tests:
print(f'"{s}" -> {str(is_palindrome(s)).lower()}')function isPalindrome(s) {
const isAlnum = (ch) => /[a-z0-9]/i.test(ch);
let lo = 0, hi = s.length - 1;
while (lo < hi) {
if (!isAlnum(s[lo])) lo++; // skip spaces and punctuation
else if (!isAlnum(s[hi])) hi--;
else if (s[lo].toLowerCase() !== s[hi].toLowerCase()) return false; // mismatch
else { lo++; hi--; } // match: both pointers move in
}
return true;
}
const tests = ["A man, a plan, a canal: Panama", "race a car", " "];
for (const s of tests) console.log(`"${s}" -> ${isPalindrome(s)}`);package main
import "fmt"
func isAlnum(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'
}
func lower(c byte) byte {
if c >= 'A' && c <= 'Z' {
return c + ('a' - 'A')
}
return c
}
func isPalindrome(s string) bool {
lo, hi := 0, len(s)-1
for lo < hi {
switch {
case !isAlnum(s[lo]):
lo++ // skip spaces and punctuation
case !isAlnum(s[hi]):
hi--
case lower(s[lo]) != lower(s[hi]):
return false // mismatch: not a palindrome
default:
lo++ // match: both pointers move in
hi--
}
}
return true
}
func main() {
tests := []string{"A man, a plan, a canal: Panama", "race a car", " "}
for _, s := range tests {
fmt.Printf("%q -> %v\n", s, isPalindrome(s))
}
}static bool IsPalindrome(string s)
{
int lo = 0, hi = s.Length - 1;
while (lo < hi)
{
if (!char.IsLetterOrDigit(s[lo])) lo++; // skip spaces and punctuation
else if (!char.IsLetterOrDigit(s[hi])) hi--;
else if (char.ToLower(s[lo]) != char.ToLower(s[hi])) return false; // mismatch
else { lo++; hi--; } // match: both pointers move in
}
return true;
}
string[] tests = { "A man, a plan, a canal: Panama", "race a car", " " };
foreach (var s in tests)
Console.WriteLine($"\"{s}\" -> {(IsPalindrome(s) ? "true" : "false")}");All six print:
"A man, a plan, a canal: Panama" -> true
"race a car" -> false
" " -> true
- C++'s
isalnumandtolowermust be given anunsigned char; a plaincharwith a negative value is undefined behaviour. - Go checks the bytes by hand because the input is ASCII. For Unicode text you'd walk runes instead of bytes.
Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Clean, reverse, compare | O(n) | O(n) for the copies |
| Two pointers in place | O(n) | O(1) |
Every step moves at least one pointer inward, and they start n - 1 apart, so the loop runs at most n times.
Edge cases and common mistakes
- Only punctuation or spaces (
" ",".,"): nothing to compare, sotrue. - Digits count:
"0P"isfalse, since 0 and p differ. Don't drop digits along with punctuation. - Forgetting case: compare lowercase forms, or "Aa" fails.
- Skipping with an inner
whilethat runs past the other pointer: if you writewhile not s[lo].isalnum(): lo += 1, addlo < hito the condition, or a string like".,"runs off the end. - JavaScript's
[...s].reverse()splits by code points, which is fine here, buts.split("").reverse()breaks emoji. Another reason to compare in place.
Where it's used in real apps
- Input normalisation: "ignore case, spaces and punctuation" is the same clean-up search boxes and username checks apply before comparing text, as you saw with canonical keys in Group Anagrams.
- Biology: tools that analyse DNA look for palindromic stretches, where a strand read forwards matches its partner strand read backwards. Many enzymes cut DNA at exactly such sites.
- In-place reversal: reversing an array or a string in place (swapping
loandhiuntil they meet) is the same two-pointer walk, used inside many library routines.
Quick quiz
1. Why is the two-pointer version O(1) space when the copy version is O(n)?
It reads the original string where it is and keeps only two indexes. The copy version stores a cleaned string and its reverse, both up to n characters.
2. What does
"0P" return, and why is it a common bug?
false: 0 and p are different. People who remove everything that isn't a letter drop the 0 and wrongly get "p", a palindrome.
3. How many times can the loop run for a string of length n?
At most n - 1. Each iteration moves at least one pointer one step inward, and they start n - 1 apart.
4. How would you check "palindrome after deleting at most one character" (LeetCode 680)?
Run the same two pointers. At the first mismatch, try skipping either s[lo] or s[hi], and check whether the remaining middle part is a palindrome. Still O(n).
Solved it yourself and understood the optimal approach? Mark it to track your progress.