← All Lessons Lesson 21 / 68
Lesson 21

Checking if a String is a Palindrome

What is a Palindrome?

A string is just a piece of text — a row of characters like letters, numbers, or symbols. A palindrome is a special kind of text that reads the same way forward and backward.

Think of the word madam. Read it left to right: m-a-d-a-m. Now read it right to left: m-a-d-a-m. It is exactly the same. That makes madam a palindrome. The word hello is not, because reading it backward gives olleh, which is different.

The Goal

You are given a string s. You must write a function that returns true if the string is a palindrome, and false if it is not.

bool palindromeChecker(string s) {

}

The function returns a bool, which is a value that is either true or false.

Two Important Rules Before Checking

Real text often has capital letters, spaces, and punctuation. The problem asks us to ignore those. So before we check, we clean the string in two steps:

  1. Change all uppercase letters to lowercase. This way A and a count as the same letter. So Mom is treated like mom.
  2. Remove every character that is not alphanumeric. *Alphanumeric* means letters and digits only: az, AZ, and 09. Spaces, commas, and other symbols are thrown away.

After cleaning, we check if the leftover text reads the same forward and backward.

Working Through the Examples

Example 1: Input is s = amannama. There is nothing to clean here — all letters, already lowercase. Read it forward: amannama. Read it backward: amannama. They match, so the output is true.

Example 2: Input is s = racecar. Forward it is racecar, and backward it is also racecar. So this is true as well.

A Simple Way to Think About the Check

A common, easy idea is the two-pointer method. Imagine putting one finger at the start of the cleaned string and another finger at the end. Compare the two characters they point to:

  • If they are different, the string is not a palindrome — return false right away.
  • If they are the same, move the start finger one step right and the end finger one step left.

Keep going until your fingers meet in the middle. If you never found a mismatch, the string is a palindrome — return true.

This works because a palindrome must mirror itself: the first character must equal the last, the second must equal the second-to-last, and so on.

Checking if a String is a Palindrome
Diagram — click to zoom (scroll / drag to pan)