Browse curriculum

Palindrome Check

A palindrome check tests whether a string reads the same forwards and backwards.

7 CHARS · 3 PAIRS

MATCH

L

r

0

a

1

c

2

e

3

c

4

a

5

R

r

6

 

'r' at 0 matches 'r' at 6. Move both pointers inwards.

Next

'a' at 1 matches 'a' at 5. Move both pointers inwards.

Word

Intuition

A palindrome reads the same forwards and backwards. We can verify this by comparing characters from the outside in. If any pair doesn't match, it's not a palindrome.

Concept

  • Two Pointers: One at start, one at end.
  • Comparison: Check if characters at pointers are equal.
  • Termination: Stop when pointers meet or cross.

How it Works

Algorithm:

  1. Initialize L = 0, R = n - 1.
  2. While L < R:
  3. If str[L] != str[R], return False.
  4. L++, R--.
  5. Return True.

Step-by-Step Breakdown

Watch the visualization:

  • See pointers move inwards.
  • If a mismatch is found, the process stops immediately (Red).
  • If pointers meet, it's a palindrome (Green).

When to Use

  • Verifying palindromes.
  • Checking symmetry in arrays/strings.

When NOT to Use

  • N/A

How to Identify

"Is palindrome", "Read same forwards and backwards".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

Why use two pointers instead of reversing and comparing?

Both are O(N) time, but the two-pointer scan uses O(1) extra space and can stop at the first mismatch. Reversing allocates a second string before any comparison happens.


Do I have to compare all N characters?

No, only until the pointers meet, which is N/2 comparisons. The middle character of an odd-length string is its own mirror and never needs checking.


How do I ignore case and punctuation?

Advance each pointer past non-alphanumeric characters before comparing, and compare the two characters case-folded. Doing it inside the scan preserves the O(1) space that pre-cleaning the string would cost.