AlgoMaster Logo

Valid Palindrome

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Two-pointer: Clean String

Intuition:

The problem requires us to determine if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. The basic idea is to first clean the string by removing all non-alphanumeric characters and converting everything to a consistent case (lowercase). Then, use two pointers to compare characters from the start and end of the string moving inwards.

Steps:

  1. Create a cleaned version of the string that contains only lowercase alphanumeric characters.
  2. Initialize two pointers, one at the start and another at the end of the cleaned string.
  3. Increment and decrement the pointers towards the center, checking if the characters are the same.
  4. If you reach the center with all characters matching, the string is a palindrome.

Code:

2. Two-pointers: O(1) space

Intuition:

The previous solution effectively checks the palindrome by cleaning up the string first. However, we can optimize it to not require extra space for a cleaned version. Instead, directly use two pointers on the input string to perform the checking while skipping over non-alphanumeric characters.

Steps:

  1. Initialize two pointers, left at the start and right at the end of the string.
  2. While left is less than right:
    • Increment the left pointer until an alphanumeric character is found.
    • Decrement the right pointer until an alphanumeric character is found.
    • Compare the characters. If they are not equal, the string is not a palindrome.
    • Move the pointers inward and repeat.
  3. If the entire string is processed without mismatches, it is a palindrome.

Code: