Solving Valid Palindrome — JavaScript

Valentin Placido
2 min readJul 3, 2020

--

This week I have been practicing on LeetCode more often and have complete various problems. But one that sticks out the most is problem 125 Valid Palindrome

Given the instructions from the problem we are given a string we have to determine if it a palindrome considering only alphanumeric characters, ignoring cases, and defining empty strings as a valid palindrome.

To start off we will have to remove all the non alphanumeric characters from the string if there are any. This can be done with the replace function. Along with having only valid characters in the string we want the string to be either all lowercase or uppercase, for now I set the string to be lowercase.

s = s.replace(/\W/g, ‘’).toLowerCase();

Next we have to iterate through the string and test if a character found in the string does not match the other side then to return false as it is not a palindrome. To accomplish this we have a for loop that will iterate through half of the string’s length since we will compare the front half of the string to the back half of the string. Next a conditional is needed to determine if the frontside of the string i is not equal to the back half of the string using the length of the string minus i and minus i which gives us the position of the character on the opposite side. If the case is true return false as the string is not a valid palindrome.

for (let i = 0; i < s.length/2; i++) {
if (s[i] !== s[s.length-i-1]) {
return false;
}
}

The final step to solve the problem will be to return true since if the string is a valid palindrome the for loop would have returned false before the function reached the final line of code. Putting all of this together we get the following solution.

The solution passes all the test cases with a Runtime of 88ms and 37.8 mb of Memory used.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response