Solve LeetCode problem #125 Valid Palindrome

In this blog, we'll be solving the Valid Palindrome problem on LeetCode.

Problem Overview

The task is to check whether a given string is a valid palindrome, considering alphanumeric characters and ignoring cases.

A palindrome is a string that reads the same backward as forward.

Example:

For instance, consider the string: "A man, a plan, a canal: Panama".

  • After sanitization, removing non-alphanumeric characters and converting to lowercase, the string becomes "amanaplanacanalpanama".
  • This sanitized string is a valid palindrome because if you read it backward, it's the same as reading it forward.

Other examples are 'aba', 'abba', 'racecar', etc.

Approach

Check the video solution:

The solution employs a two-pointer technique:

  1. Sanitization: The input string is sanitized by removing non-alphanumeric characters and converting it to lowercase.
  2. Pointers: Initialize two pointers, left at the start and right at the end of the sanitized string.
  3. Comparison: Iterate through the string while left <= right.
    • Compare characters at left and right.
    • If they don't match, return false.
    • Move left pointer forward and right pointer backward.
  4. If the comparison continues without mismatch, return true.

JavaScript Solution

Here's the JavaScript solution implementing the described approach:

1var isPalindrome = function (s) {
2 const sanitaizedString = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()
3
4 let left = 0
5 let right = sanitaizedString.length - 1
6
7 while (left <= right) {
8 const leftChar = sanitaizedString[left]
9 const rightChar = sanitaizedString[right]
10
11 if (leftChar !== rightChar) return false
12
13 left++
14 right--
15 }
16
17 return true
18}

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostInvert Binary Tree
Next PostSolve LeetCode problem #121 Best Time to Buy and Sell Stock