Leetcode Practice

LC 125. Valid Palindrome

Last updated
Reading time
1 min read

The problem

First Solution - O(n)O(n) Time

This version of the solution is simple after filtering out non-alphanumerics with regex. Compare the original and reversed filtered to check if they're the same.

function isPalindrome(s: string): boolean {
  let str = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()
  return str === str.split('').reverse().join('')
}

Two-pointers solution

This solution checks each character using pointers that start at the two ends of the string and move inward.

function isPalindrome(s: string): boolean {
  let str = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()
  let left = 0
  let right = str.length - 1
  while (left < right) {
    if (str[left] !== str[right]) {
      return false
    }
    left++
    right--
  }
  return true
}