Frontend School

Valid Alphanumeric Palindrome

DSA
easy

Valid Alphanumeric Palindrome

Easy
String
Two Pointers

Overview

In text processing and data validation, efficiently checking for palindromes is a common task. This problem challenges you to determine if a given string is a palindrome, but with a twist: you must consider only alphanumeric characters and ignore case. This is crucial for normalizing user input or text data before analysis, ensuring that the core content is evaluated regardless of formatting or capitalization.

What you need to do / Task

Implement a function isPalindrome that takes a string s and returns true if it is an alphanumeric palindrome, and false otherwise. Your implementation must satisfy the following:

  1. Character Filtering: Only consider alphanumeric characters (letters a-z, A-Z, and digits 0-9). All other characters (e.g., spaces, punctuation, symbols) should be ignored.
  2. Case Insensitivity: When comparing letters, treat uppercase and lowercase letters as the same (e.g., 'A' is equivalent to 'a').
  3. Palindrome Check: After applying the above rules, determine if the resulting sequence of alphanumeric characters reads the same forwards and backwards.

Input & output

  • Input: s (string)
    • A string consisting of printable ASCII characters.
  • Output: A boolean value
    • true if s is an alphanumeric palindrome, false otherwise.

Clarifications

  • Empty string: An empty string "" is considered a valid palindrome.
  • String with only non-alphanumeric characters: If the string s contains no alphanumeric characters after filtering, it should also be considered a valid palindrome (e.g., ".," becomes an empty string, which is a palindrome).

Examples

1

Example 1

Input:

s = "A man, a plan, a canal: Panama"

Output:

true

Note:

After converting to lowercase and removing non-alphanumeric characters, it becomes "amanaplanacanalpanama", which is a palindrome.

2

Example 2

Input:

s = "race a car"

Output:

false

Note:

After converting to lowercase and removing non-alphanumeric characters, it becomes "raceacar", which is not a palindrome.

3

Example 3

Input:

s = " "

Output:

true

Note:

After removing non-alphanumeric characters, the string becomes empty, which is considered a palindrome.

4

Example 4

Input:

s = "Madam"

Output:

true

Note:

After converting to lowercase, it becomes "madam", which is a palindrome.

Constraints

Constraints & assumptions

  • 0 <= s.length <= 2 * 10^5
  • s consists only of printable ASCII characters.

What interviewers evaluate

  • Correctness: Does the solution accurately identify all valid alphanumeric palindromes and non-palindromes?
  • Efficiency: Is the solution optimal in terms of time and space complexity?
  • Edge Cases: Does the code handle all specified edge cases, such as empty strings or strings with no alphanumeric characters?
  • Code Quality: Is the code clean, readable, well-structured, and easy to understand?

Loading editor...