Step through Find Palindrome

Hello all, One of the first algorithms I did was find the palindrome. A palindrome is a word, phrase or sequence of characters that reads the same left to right & right to left. When I initially came across this problem I just wanted to solve it to get the test to past, aka brute force. I didn’t consider time complexity, much less gave thought to a simpler way. My initial amateur approach was checking every single letter that's in the argument. Whether it was true or false, the function will check every single character.

Consider the example in the first screenshot, ‘race a car’, on line 238 I’m using regex on the s parameter and then line 239 creating a new variable word and setting that to s, splitting, reversing and joining. Then line 240 returning true if s is strictly equal to word. It works…but it’s slow!

This solution has more lines of code but it’s faster. Instead of checking every element in the string, we can use a two pointer method and check from the beginning and the end of the string. Line 239 we use regex to account for spaces and symbols. Lines 240 & 241 are our pointers, i starts at the beginning & j starts at the end. Using the while loop since I am counting from both ends of the strings, line 244 is where I check if the value at the current indexes are the same. With the “race a car” string, once we get to ‘e’ there’s no need to check the rest of the string because meeting that condition immediately makes it false. Why is this a better a solution? Imagine the string was 200 characters long, if we can reach a false condition at index 25, there’s no need to continue iterating the remaining 185 indexes just to get the same result.

I hope this was helpful ! Happy coding !

The sassy developer