One Pager Cheat Sheet
- You can write a method using
O(n)time andO(1)space complexity to check if a givenstringof length100000or less is a palindrome, taking into account non-alphanumerical characters. - The
given stringis apalindromeif it reads the same forwards as it does backwards. - With built-in methods, you can easily
reverse()or[::-1]aStringand then compare it to the original to check if it is apalindrome. - By utilizing two variables,
lowandhigh, to represent the starting and ending indices of a string to be checked, and using awhile loopto compare characters at these indices, we can determine if a string is a palindrome or not. - The code reverses a string by looping over the characters, swapping the characters and keeping track of the
startandendindexes using atempvariable, and then joining the characters of thestr_copylist to return the reversed string. - We can reduce complexity by using
two pointersinstead of one and only have to dolen(str)/2iterations of thewhile loopin order to validate if a string is a palindrome. - Comparing characters of a
stringwith two pointers,startpointing to the beginning andendpointing to the last character, the example inputracecarshows us the initial comparisons. - The runtime of the code is
O(n), withO(1)space complexity, wherenis the length of the string, since it iterates linearly with a constant space overhead.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx80
}var assert = require('assert');​function isPalindrome(str) { if (!str || str === '') { return true; } else { let left = 0; let right = str.length - 1; let leftChar; let rightChar;​ while (left < right) { leftChar = str.charAt(left).toLowerCase(); rightChar = str.charAt(right).toLowerCase();​ if (isAlphaNumeric(leftChar) && isAlphaNumeric(rightChar)) { if (leftChar == rightChar) { left++; right--; } else { return false; } } else { if (!isAlphaNumeric(leftChar)) { left++; } if (!isAlphaNumeric(rightChar)) { right--; } } }​OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.


