Valid Palindrome

Determine if string is a palindrome, ignoring non-alphanumeric characters and case.

Easy

Examples

Example 1: "A man, a plan, a canal: Panama" → true

Implementation

Ruby

  # 🔁 Two Pointers Example
  #
  # Problem: Valid Palindrome
  # Given a string, determine if it is a palindrome, ignoring non-alphanumeric characters and case.
  #
  # Input Examples:
  #   valid_palindrome("A man, a plan, a canal: Panama") => true
  #   valid_palindrome("race a car") => false
  #
  # Time Complexity: O(n), where n is the length of the string.
  def valid_palindrome(s)
    left, right = 0, s.length - 1

    while left < right
      # Skip non-alphanumeric characters on the left
      left += 1 until left >= right || s[left].match?(/[a-zA-Z0-9]/)

      # Skip non-alphanumeric characters on the right
      right -= 1 until left >= right || s[right].match?(/[a-zA-Z0-9]/)

      # Compare lowercase versions of characters
      return false if s[left].downcase != s[right].downcase

      left += 1
      right -= 1
    end

    true

Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1)

Patterns & Techniques

Problem Details

Category: Pointer And Sliding Window
Difficulty: Easy
Module: PointerAndSlidingWindow
Method: valid_palindrome
← Back to Pointer And Sliding Window