Valid Palindrome

Updated on 30 June, 2025
Valid Palindrome header image

Problem Statement

In the given task, we need to determine if a string, referred to as s, qualifies as a palindrome after undergoing specific transformations. A palindrome is a sequence that reads the same backward as forward. For the purposes of this task, the transformations involve converting all uppercase letters to lowercase and removing all non-alphanumeric characters, which includes anything other than letters and numbers. The output will be true if the modified string is a palindrome, and false otherwise.

Examples

Example 1

Input:

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

Output:

true

Explanation:

"amanaplanacanalpanama" is a palindrome.

Example 2

Input:

s = "race a car"

Output:

false

Explanation:

"raceacar" is not a palindrome.

Example 3

Input:

s = " "

Output:

true

Explanation:

s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

Constraints

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

Approach and Intuition

To solve this problem, let's break down the examples provided and extract the intuition and methodology we can use:

  1. Convert all uppercase characters in the string to lowercase. This ensures that the comparison is case-insensitive, treating 'A' and 'a' as equivalent.
  2. Remove all non-alphanumeric characters. This step requires scanning each character in the string and excluding any that are not letters or numbers.
  3. Check if the resulting string is a palindrome. This can be done by comparing the string to its reverse; if they are the same, the string is a palindrome.

Based on each example:

  • Example 1: Clearing all characters that are not alphanumeric and converting the rest to lower case provides a straightforward, long palindrome.
  • Example 2: Even after cleaning the input string, the sequence does not read the same forwards and backwards, indicating it isn't a palindrome.
  • Example 3: A string composed entirely of spaces results in an empty string after cleaning. Since an empty string trivially reads the same in both directions, it is considered a palindrome.

With these steps and considerations in mind, the implementation can systematically check any input string for its palindrome status post-transformation.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    bool checkPalindrome(string str) {
        for (int start = 0, end = str.length() - 1; start < end; start++, end--) {
            while (start < end && !isalnum(str[start])) start++;
            while (start < end && !isalnum(str[end])) end--;
    
            if (tolower(str[start]) != tolower(str[end])) return false;
        }
    
        return true;
    }
};

The provided C++ function, checkPalindrome, efficiently determines if a given string is a valid palindrome while disregarding non-alphanumeric characters. Here's a concise explanation of how this function operates:

  • It uses two index pointers, start and end, to traverse the string from the beginning and the end simultaneously.
  • The loop continues until the start index is less than the end index.
  • Within the loop, both pointers skip any non-alphanumeric characters using nested while loops.
  • It then compares the characters at these indices, after converting them to lowercase, to check if they are the same. If at any point they are not, the function immediately returns false.
  • If the loop completes without finding mismatched characters, the function returns true, indicating the string is a palindrome.

This method efficiently handles strings with mixed characters, focusing only on alphanumeric values and ignoring case sensitivity. It ensures that only relevant characters are considered, making the palindrome check robust and accurate.

java
class Solution {
    public boolean checkPalindrome(String str) {
        for (int start = 0, end = str.length() - 1; start < end; start++, end--) {
            while (start < end && !Character.isLetterOrDigit(str.charAt(start))) {
                start++;
            }
            while (start < end && !Character.isLetterOrDigit(str.charAt(end))) {
                end--;
            }
    
            if (
                Character.toLowerCase(str.charAt(start)) !=
                Character.toLowerCase(str.charAt(end))
            ) return false;
        }
    
        return true;
    }
}

The provided Java solution defines a method checkPalindrome to determine whether a given string is a palindrome. Ignore any non-alphanumeric characters and make a case-insensitive comparison. Here's a breakdown of how the method works:

  • Iterate over the string from both ends simultaneously with two pointers, start and end.
  • Increment the start pointer if the character at start is not a letter or digit.
  • Decrement the end pointer if the character at end is not a letter or digit.
  • Compare the characters at start and end after converting them to lowercase. If they are not the same, return false.
  • If all comparisons are valid, the loop completes successfully and the method returns true, confirming the string is a palindrome.

The approach efficiently checks for a palindrome while disregarding non-alphanumeric characters and handling case differences.

c
bool checkIfPalindrome(char* str) {
    int start = 0;
    int end = strlen(str) - 1;
    while (start < end) {
        while (start < end && !isalnum(str[start])) {
            start++;
        }
        while (start < end && !isalnum(str[end])) {
            end--;
        }
        if (tolower(str[start]) != tolower(str[end])) return false;
        start++;
        end--;
    }
    return true;
}

This C program checks if a given string is a palindrome while only considering alphanumeric characters and ignoring cases. The function checkIfPalindrome takes a character array str as its parameter. It initializes two pointers, start and end, to point to the beginning and the end of the string respectively. The function then uses a while loop to iteratively compare the characters at the start and end positions, moving inward.

  • The inner loops skip non-alphanumeric characters by incrementing start and decrementing end respectively.
  • Characters are compared in a case-insensitive manner using the tolower function.
  • If a mismatch is found (characters at start and end are not the same when converted to lowercase), the function immediately returns false.
  • If the entire string (or relevant part of it) checks out as symmetric, the function returns true.

This approach efficiently validates whether the sanitized version of the input string is a palindrome.

js
var checkPalindrome = function (str) {
    let start = 0;
    let end = str.length - 1;
    while (start < end) {
        while (start < end && !validChar(str[start])) {
            start++;
        }
        while (start < end && !validChar(str[end])) {
            end--;
        }
        if ((str[start] + "").toLowerCase() !== (str[end] + "").toLowerCase())
            return false;
        start++;
        end--;
    }
    return true;
};
function validChar(ch) {
    const code = ch.charCodeAt();
    return (
        (code >= "a".charCodeAt() && code <= "z".charCodeAt()) ||
        (code >= "A".charCodeAt() && code <= "Z".charCodeAt()) ||
        (code >= "0".charCodeAt() && code <= "9".charCodeAt())
    );
}

This solution determines if a given string is a palindrome by considering only alphanumeric characters and ignoring cases. The process involves the following steps:

  1. Initialize two pointers, start at the beginning of the string and end at the last character.
  2. Use a while loop to move start and end closer to the center of the string, skipping over non-alphanumeric characters.
  3. Check if characters at the start and end positions are the same (ignoring case). If they are not, the function returns false immediately.
  4. If all valid characters from start to end are palindromic, the function returns true.

The validChar function is used to check if a character is alphanumeric using its ASCII values. This makes the solution efficient by ensuring that only relevant characters are considered in the palindrome check.

python
class Solution:
    def checkPalindrome(self, text: str) -> bool:
            
        left_index, right_index = 0, len(text) - 1
    
        while left_index < right_index:
            while left_index < right_index and not text[left_index].isalnum():
                left_index += 1
            while left_index < right_index and not text[right_index].isalnum():
                right_index -= 1
    
            if text[left_index].lower() != text[right_index].lower():
                return False
    
            left_index += 1
            right_index -= 1
    
        return True

This Python solution checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. The function checkPalindrome processes the string by using two pointers:

  • Initialize left_index at the start and right_index at the end of the string.
  • Use a while loop to move left_index to the right until an alphanumeric character is found and similarly move right_index to the left.
  • Compare the characters at left_index and right_index. If they are not the same, return False.
  • If the characters match, move both pointers closer to the center.
  • Continue this process until the pointers meet or cross, at which point the function returns True, confirming the string is a palindrome.

Ensure proper functionality by testing with various inputs, including strings with special characters and mixed case letters. This method is efficient with a time complexity of O(n), where n is the length of the string, and it handles edge cases effectively.

Comments

No comments yet.