DSA AnimatorREVISION VIDEOS
← Back to problems
New

Valid Palindrome — LeetCode 125 video explanation

You get a string. Ignore spaces and symbols, and treat capital and small letters as the same. Does it read the same forwards and backwards?

Loading videos…

DSA Animator › DSA Revision › Strings › Valid Palindrome

Key moments in the Valid Palindrome video

0:04Problem0:12Example0:22Brute force0:29Key idea0:43Dry run1:02Code1:13Takeaway

What you will learn

Remember: two pointers from both ends check a palindrome in place. Skip what does not count, and compare the rest in lowercase. The video solves Valid Palindrome (LeetCode 125, Easy) with the Two Pointers pattern from the Strings topic, and you can replay every step in the interactive Valid Palindrome animation.

Valid Palindrome video transcript

Problem

You get a string. Ignore spaces and symbols, and treat capital and small letters as the same. Does it read the same forwards and backwards?

Example

Take the string taco cat, with an exclamation mark at the end. After cleaning it becomes t, a, c, o, c, a, t. It reads the same backwards, so the answer is true.

Brute force

You could build a cleaned copy, reverse it, and compare. That works, but it uses O of n extra space.

Key idea

Use two pointers, left at the start and right at the end. If a pointer is on a space or a symbol, move it past. Otherwise compare the two characters in lowercase. If they differ, return false, otherwise move both pointers inward.

Dry run

Left is on capital T, and right is on the exclamation mark. The mark is a symbol, so right moves back. Capital T and small t match in lowercase. a and a match. c and c match. Now right is on the space, so right moves back again. The pointers meet on o, with no mismatch. So the answer is true.

Code

In code, loop while left is less than right. Skip anything that is not a letter or a digit. Compare in lowercase, and return false on a mismatch. Time is O of n, and space is O of 1.

Takeaway

Remember: two pointers from both ends check a palindrome in place. Skip what does not count, and compare the rest in lowercase.

More Strings revision videos

← All 185 DSA revision videos