Valid Palindrome - Leetcode Solution


💡 Step-by-Step Thought Process

  1. Understand the problem: Determine if a string is a palindrome, ignoring non-alphanumeric characters and case differences.
  2. Get the length n of the input string s.
  3. Initialize two pointers: L to 0 (start) and R to n-1 (end).
  4. While L is less than R:
    • If the character at s[L] is not alphanumeric, increment L and continue.
    • If the character at s[R] is not alphanumeric, decrement R and continue.
    • If the lowercase characters at s[L] and s[R] are not equal, return False.
  5. Increment L and decrement R to check the next pair.
  6. Return True if all checked characters match, indicating a palindrome.

Code Solution


                

                

                

                

Detailed Explanation

Understanding the Problem

The "Valid Palindrome" problem asks us to determine whether a given string is a palindrome. A palindrome is a sequence that reads the same backward as forward. However, this variant of the problem ignores all non-alphanumeric characters and is case-insensitive. For example, "A man, a plan, a canal: Panama" is considered a valid palindrome.

Two-Pointer Technique

To solve this efficiently without using additional space to store a cleaned version of the string, we apply the two-pointer approach. We use two indices, one starting from the beginning of the string (L) and the other from the end (R), moving inward.

At each step, we skip any character that is not alphanumeric by advancing the pointers. If both characters are alphanumeric, we compare their lowercase versions. If at any point the characters differ, the string is not a palindrome, and we return false.

Step-by-Step Strategy

  1. Initialize L = 0 and R = s.length - 1.
  2. While L < R:
    • If s[L] is not alphanumeric, increment L.
    • If s[R] is not alphanumeric, decrement R.
    • Compare lowercase(s[L]) and lowercase(s[R]). If they differ, return false.
    • If they match, increment L and decrement R.
  3. If the loop completes without mismatches, return true.

Why This Works

This method is efficient because it avoids the overhead of creating a new filtered string. By using the two-pointer approach, we ensure that we check character pairs directly within the original string. Lowercasing both characters standardizes comparison and skipping non-alphanumeric characters ensures compliance with the problem’s constraints.

Time and Space Complexity

The solution runs in O(n) time, where n is the length of the input string, since each character is visited at most once. The space complexity is O(1), as we only use a constant number of pointers and comparisons, making this approach optimal for large strings.

Get Personalized Support at AlgoMap Bootcamp 💡