Practice · 02 Sorted Arrays: Two Pointers · 1/5

Valid Palindrome

Check if a string reads the same from both ends.

EasyLeetCode #125
Solve on LeetCode ↗

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, return true if it is a palindrome, or false otherwise.

InputCleanedOutput
"A man, a plan, a canal: Panama"amanaplanacanalpanamatrue
"race a car"raceacarfalse
" "(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
}

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.

T0a1c2o3␣4c5a6t7!8skipR on "!": not a letter or digit → skip itT = t (ignore case), a = a: equal → both pointers step inskipc = c, then the space is skipped and the pointers meet at "o"no mismatch before they met → true · O(n) time, O(1) extra space
"Taco cat!" checked in place. The right pointer skips "!", then T matches t, a matches a and c matches c. The left pointer reaches "o", the space is skipped, and the pointers meet: no mismatch, so it's a palindrome.

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

  1. lo = 0, hi = len(s) - 1.
  2. While lo < hi:
    • if s[lo] isn't a letter or digit, move lo right;
    • else if s[hi] isn't, move hi left;
    • else if their lowercase forms differ, return false;
    • else move both inward.
  3. 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");
}

All six print:

"A man, a plan, a canal: Panama" -> true
"race a car" -> false
" " -> true
  • C++'s isalnum and tolower must be given an unsigned char; a plain char with 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

ApproachTimeExtra space
Clean, reverse, compareO(n)O(n) for the copies
Two pointers in placeO(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, so true.
  • Digits count: "0P" is false, since 0 and p differ. Don't drop digits along with punctuation.
  • Forgetting case: compare lowercase forms, or "Aa" fails.
  • Skipping with an inner while that runs past the other pointer: if you write while not s[lo].isalnum(): lo += 1, add lo < hi to the condition, or a string like ".," runs off the end.
  • JavaScript's [...s].reverse() splits by code points, which is fine here, but s.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 lo and hi until 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.