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:
- Sanitization: The input string is sanitized by removing non-alphanumeric characters and converting it to lowercase.
- Pointers: Initialize two pointers,
left
at the start andright
at the end of the sanitized string. - Comparison: Iterate through the string while
left <= right
.- Compare characters at
left
andright
. - If they don't match, return
false
. - Move
left
pointer forward andright
pointer backward.
- Compare characters at
- 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()34 let left = 05 let right = sanitaizedString.length - 167 while (left <= right) {8 const leftChar = sanitaizedString[left]9 const rightChar = sanitaizedString[right]1011 if (leftChar !== rightChar) return false1213 left++14 right--15 }1617 return true18}
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
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: