# LeetCode Valid Palindrome: O(N) Time and O(1) Space with Two Pointers

## Overview

LeetCode Valid Palindrome: It could be solved in O(N) Time and O(1) Space with Two Pointers to scan the characters from both end and compare the characters.

## LeetCode Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
`"A man, a plan, a canal: Panama"` is a palindrome.
`"race a car"` is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

## Solution: O(N) Time and O(1) Space with Two Pointers

This problem is an easy one, but a little bit change from the regular palindrome problem, the algorithm is straightforward just scan through the string using head and tail pointer until these two pointer hit each other, and by definition, determine if the character pointed at head and tail is the same as each other(ignoring  cases and ignoring those non-alphanumeric characters). If all are the “same”, then it is, otherwise it is not valid. And don’t forget to check the boundary of the pointers, otherwise, there would be run time error (usually segment fault). The following code is accepted by LeetCode OJ to apss this Valid Palindrome problem and for simplicity I actually use extra O(N) space to keep the lower case version of the input:

And the following two implementation slightly differs from the above, just for your further reference.

Also take a look at this similar problem but applies to Linked List: LeetCode Palindrome Linked List: O(1) Space

## Summary

LeetCode Valid Palindrome: It could be solved in O(N) Time and O(1) Space with Two Pointers to scan the characters from both end and compare the characters.

Written on January 26, 2013