Hone logo
Hone
Problems

Valid Palindrome

A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. This is a fundamental concept in computer science and string manipulation, often used as a building block for more complex algorithms or as a simple test of understanding string processing. Your task is to implement a function that determines if a given string is a palindrome, considering only alphanumeric characters and ignoring cases.

Problem Description

Your goal is to write a function that takes a string as input and returns TRUE if the string is a palindrome, and FALSE otherwise.

The palindrome check should adhere to the following requirements:

  • Alphanumeric Characters Only: Only consider letters (a-z, A-Z) and digits (0-9) when checking for palindromic properties.
  • Case Insensitivity: Treat uppercase and lowercase letters as equivalent (e.g., 'A' is the same as 'a').
  • Ignore Non-Alphanumeric Characters: Any characters that are not letters or digits (e.g., spaces, punctuation, symbols) should be disregarded.

Expected Behavior:

The function should process the input string, filter out non-alphanumeric characters, convert all remaining characters to a consistent case (e.g., lowercase), and then check if the resulting sequence of characters reads the same forwards and backward.

Edge Cases to Consider:

  • An empty string is considered a valid palindrome.
  • A string with only one character is considered a valid palindrome.
  • Strings containing only non-alphanumeric characters should be treated as empty strings and thus valid palindromes.

Examples

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: TRUE
Explanation: After removing non-alphanumeric characters and converting to lowercase, the string becomes "amanaplanacanalpanama". This string reads the same forwards and backward.

Example 2:

Input: "race a car"
Output: FALSE
Explanation: After processing, the string becomes "raceacar". This string reads differently backward ("racacear").

Example 3:

Input: " "
Output: TRUE
Explanation: The string contains only a space, which is a non-alphanumeric character. After processing, it effectively becomes an empty string, which is a valid palindrome.

Example 4:

Input: "0P"
Output: FALSE
Explanation: After processing, the string remains "0p". This string reads differently backward ("p0").

Constraints

  • The length of the input string s will be between 0 and 2 * 10^5, inclusive.
  • The input s will consist of printable ASCII characters.

Notes

Consider using two pointers, one starting from the beginning of the processed string and another from the end, to efficiently compare characters. You might also think about how to efficiently filter and normalize the string before performing the palindrome check.

Loading editor...
plaintext