The problem. A phrase is a palindrome if, after turning every uppercase letter into lowercase and removing everything that isn't a letter or a digit, it reads the same forwards and backwards. Given a string s, return true if it is a palindrome.
s = "No lemon, no melon" -> true
s = "A man, a plan, a canal: Panama" -> true
s = "race a car" -> false ("raceacar" backwards is "racaecar")
s = " " -> true (nothing left: an empty string reads the same)A palindrome's first character equals its last, its second equals its second-to-last, and so on — the two-pointer check. The only twist is the noise: spaces, commas and case. The obvious fix is to clean the string first. The better fix is to let each pointer skip the characters that don't count, so no cleaned copy is ever made.
Build the cleaned lowercase string, then check it equals its own reverse.
function isPalindrome(s) { const clean = s.toLowerCase().replace(/[^a-z0-9]/g, ""); // keep letters and digits only return clean === [...clean].reverse().join(""); // equal to its own reverse?}Time O(n), space O(n). Three passes — clean, reverse, compare — and two new strings as long as the input.
Start at both ends. If the left character isn't a letter or digit, step past it; same on the right. When both point at real characters, compare them ignoring case: a mismatch means false, a match moves both inwards.
Grey characters are skipped; each matching pair turns green. Try the one that isn't a palindrome.
function isPalindrome(s) { const ok = (ch) => /[a-z0-9]/i.test(ch); // letters and digits count; the rest is skipped let left = 0, right = s.length - 1; while (left < right) { if (!ok(s[left])) { left++; continue; } // skip spaces and punctuation if (!ok(s[right])) { right--; continue; } if (s[left].toLowerCase() !== s[right].toLowerCase()) return false; // a mismatch left++; right--; } return true;}Time O(n), space O(1). Every step moves at least one pointer, so there are at most n steps, and only two indexes are stored.
Approach 1 is quick to write and fine to start with; interviewers usually ask next for O(1) space, which is approach 2.
true."0P" is false because 0 and p differ."Aa" is true.left < right check in the loop guards it.