The Problem

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example: "A man, a plan, a canal: Panama"true
Example: "race a car"false

Interactive Visualization

Speed:
Character Array
Current Comparison
Press Step or Play to begin.
Code
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}
Status & Log
Press Step or Play to begin.

How It Works

Key Insight

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.

The Algorithm

  • Initialize: left = 0 (start of string), right = len(s) - 1 (end of string)
  • While left < right:
    • Skip non-alphanumeric characters by advancing left forward
    • Skip non-alphanumeric characters by moving right backward
    • Compare s[left].lower() with s[right].lower()
    • If they differ, return False immediately
    • If they match, move both pointers inward: left += 1, right -= 1
  • If all pairs matched: return True

Complexity

Time O(n)
Space O(1)

Each 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.