Palindromes
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A palindrome reads the same forwards and backwards, like madam or 1221. Checking one means comparing the first and last characters, then the second and second-last, and so on towards the middle. It is a classic test of working from both ends at once.
Practical use cases
- Web app: Special numbers on a vehicle plate service. A number-plate booking site sells fancy numbers and wants to mark palindromes like 1221 or 7337 as premium. The code compares digits from both ends and stops at the first mismatch. Each plate is checked in a few steps, even for tens of thousands of plates.
- Web app: Username and promo code rules. A contest page gives a bonus to users whose reference code is a palindrome after ignoring dashes and capital letters. The code cleans the text first and then compares both ends moving inward, so the bonus badge appears instantly on the confirmation page.
- System: DNA analysis. In genetics, a stretch of DNA that reads the same in reverse on the opposite strand marks places where certain enzymes cut. Researchers scan long gene sequences for such mirror-like patterns using the same two-ended comparison. Each position needs only a few comparisons, so even very long sequences are scanned quickly.
The story: Grandpa's Favourite Word
Grandpa Bhaskar had a game he played every evening on the verandah. He would say a word and ask, "Does it read the same backwards?" MALAYALAM, yes. NITIN, yes. CHAI, no, it becomes IAHC. Zoya always wrote the word out backwards on a slate and compared both lines. It worked, but it used up a lot of slate.
One evening Grandpa said, "No slate needed, beta. Put one finger on the first letter and another on the last. Are they the same letter? Then move both fingers one step inward and ask again."
Zoya tried it on MALAYALAM: M and M, A and A, L and L, A and A. The fingers met on the lonely Y in the middle. "If even one pair is different," Grandpa smiled, "you can stop and say no immediately." That two-fingers-closing-in idea is the two-pointer trick, and a word that passes the test is called a palindrome.
How to spot this problem, and where you need it
You must test whether text or a number reads the same in both directions, possibly ignoring punctuation and case, without wasting time building a reversed copy.
Signs you need it
- The task says palindrome, reads the same forwards and backwards, or mirror, for words, phrases or numbers.
- You are reversing a whole string and comparing it, and need a lighter method for large inputs.
- Input contains spaces, punctuation or mixed capital letters that must be ignored before comparing.
Where to use it in a project
- Fancy-number, vanity-plate and coupon features that reward symmetric codes.
- Text puzzles, quiz and game pages, and sequence searches in genetics and logs looking for symmetric patterns.
The solution
Clean the text first if needed: lowercase it and drop characters that do not count. Place one pointer at the first character and another at the last. If the two characters differ, it is not a palindrome, so stop. If they match, move both pointers one step towards the middle. If they meet or cross without a mismatch, it is a palindrome.
Payoff: Before: making a reversed copy of every code. After: half a pass with no copy, and it stops immediately on the first mismatch.
Explain it like I am 8
Stand at both ends of a skipping rope and walk toward the middle together. At every step the two of you must be holding the same letter. If you ever hold different ones, it is not a palindrome. If you meet in the middle, it is.
How it works, step by step
- Put a pointer at each end:
left = 0andright = length - 1. - Compare the two letters. If they differ, answer no straight away.
- Move inward:
left++andright--. - Repeat while left < right. When they meet or cross, every pair matched: answer yes.
- For sentences, first drop spaces and punctuation and lower-case everything, so "Was it a car or a cat I saw?" counts.
The code in four languages
PHP
<?php
// Two pointers walking toward the middle.
function isPalindrome(string $text): bool {
// keep only letters and digits, all lower-case
$s = preg_replace('/[^a-z0-9]/', '', strtolower($text));
$left = 0;
$right = strlen($s) - 1;
while ($left < $right) {
if ($s[$left] !== $s[$right]) {
return false; // one mismatch is enough
}
$left++;
$right--;
}
return true; // fingers met: everything matched
}
foreach (["Malayalam", "Was it a car or a cat I saw?", "Chai"] as $t) {
echo $t . ' => ' . (isPalindrome($t) ? 'yes' : 'no') . "\n";
}JavaScript
// Two pointers walking toward the middle.
function isPalindrome(text) {
// keep only letters and digits, all lower-case
const s = text.toLowerCase().replace(/[^a-z0-9]/g, '');
let left = 0;
let right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) {
return false; // one mismatch is enough
}
left++;
right--;
}
return true; // fingers met: everything matched
}
for (const t of ['Malayalam', 'Was it a car or a cat I saw?', 'Chai']) {
console.log(t + ' => ' + (isPalindrome(t) ? 'yes' : 'no'));
}Java
public class Main {
// Two pointers walking toward the middle.
static boolean isPalindrome(String text) {
// keep only letters and digits, all lower-case
String s = text.toLowerCase().replaceAll("[^a-z0-9]", "");
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false; // one mismatch is enough
}
left++;
right--;
}
return true; // fingers met: everything matched
}
public static void main(String[] args) {
for (String t : new String[]{"Malayalam", "Was it a car or a cat I saw?", "Chai"}) {
System.out.println(t + " => " + (isPalindrome(t) ? "yes" : "no"));
}
}
}Go
package main
import (
"fmt"
"strings"
)
// isPalindrome uses two pointers walking toward the middle.
func isPalindrome(text string) bool {
// keep only letters and digits, all lower-case
var kept strings.Builder
for _, ch := range strings.ToLower(text) {
if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') {
kept.WriteRune(ch)
}
}
s := kept.String()
left, right := 0, len(s)-1
for left < right {
if s[left] != s[right] {
return false // one mismatch is enough
}
left++
right--
}
return true // fingers met: everything matched
}
func main() {
for _, t := range []string{"Malayalam", "Was it a car or a cat I saw?", "Chai"} {
answer := "no"
if isPalindrome(t) {
answer = "yes"
}
fmt.Println(t, "=>", answer)
}
}Time: O(n) · Extra space: O(1). At most n/2 comparisons. (Cleaning the text first builds a copy, which costs extra space.)
Watch out for
- Comparing "Madam" without lower-casing: M and m look different to a computer.
- Using
left <= rightand wondering why odd words need an extra step. The middle letter never needs a partner, soleft < rightis enough. - Reversing the whole string and comparing works, but it costs extra memory that the two-pointer walk does not need.
Quick check
- Which of these is a palindrome?
- CHAI
- NITIN
- KABIR
- When should the loop stop?
- When left reaches or passes right
- When left equals the length
- After exactly 10 steps
- In a 9-letter word, how many pairs do we compare?
- 9
- 5
- 4