An interactive visualization of the two-pointer approach to check if a string is a valid palindrome. Watch the left and right pointers converge toward the middle, skipping non-alphanumeric characters.
Two Pointers LeetCode 125 ↗ Easys, return true if it is a palindrome, or false otherwise."A man, a plan, a canal: Panama" → true"race a car" → false
fun isPalindrome(s: String): Boolean { var left = 0; var right = s.length - 1 while (left < right) { while (left < right && !s[left].isLetterOrDigit()) { left++ // skip non-alphanumeric } while (left < right && !s[right].isLetterOrDigit()) { right-- // skip non-alphanumeric } if (s[left].lowercaseChar() != s[right].lowercaseChar()) { return false } left++ right-- } return true}
A palindrome reads the same forwards and backwards. Instead of creating a new cleaned string (which uses O(n) extra space), we use two pointers starting from opposite ends and moving inward. We skip any non-alphanumeric characters and compare the remaining characters case-insensitively. If every pair matches, the string is a palindrome.
left = 0 (start of string), right = len(s) - 1 (end of string)left forwardright backwards[left].lower() with s[right].lower()False immediatelyleft += 1, right -= 1TrueEach character is visited at most once by the left pointer and at most once by the right pointer, giving O(n) time. We use only a constant amount of extra space for the two pointer variables.