Taro Logo

Valid Palindrome

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+25
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.3K views
Topics:
StringsTwo Pointers

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set should we expect in the input string? Can it contain Unicode characters, emojis, or punctuation beyond standard ASCII?
  2. How should we handle an empty string or a string with no alphanumeric characters at all?
  3. Can I assume the input string fits entirely in memory, or should I design for a stream-based or out-of-memory approach?
  4. Should the validation be performed in-place to optimize space complexity, or is allocating auxiliary memory or a cleaned string acceptable?
  5. Are whitespace characters treated strictly as non-alphanumeric and ignored, or are there any special formatting rules?

Brute Force Solution

Approach

To figure out if something is the same forwards and backwards using the brute force approach, we want to completely clean up the text first and then build a brand new reversed copy of it. Finally, we can compare the clean version and the reversed version side by side to see if they match perfectly.

Here's how the algorithm would work step-by-step:

  1. Look at the original piece of text from start to finish.
  2. Throw away any punctuation marks, spaces, and symbols, and turn all uppercase letters into lowercase letters so everything looks uniform.
  3. Write down this newly cleaned version of the text on a separate piece of paper.
  4. Create another copy of the clean text, but write all of its characters in reverse order, starting from the very end and moving toward the beginning.
  5. Place the clean version and the reversed version right next to each other.
  6. Compare the two versions character by character from the beginning to the end.
  7. If every single corresponding character matches, conclude that it is a valid palindrome. If even one character does not match, conclude that it is not.

Code Implementation

def is_palindrome(input_string):
    # We extract only alphanumeric characters and lowercase them to ensure a fair comparison
    cleaned_characters = []
    for current_character in input_string:
        if current_character.isalnum():
            cleaned_characters.append(current_character.lower())

    # Reversing the clean array creates a direct mirror image to check symmetry
    reversed_characters = cleaned_characters[::-1]

    # We compare the forward and backward sequences to verify if the text reads identically
    return cleaned_characters == reversed_characters

Big(O) Analysis

Time Complexity
O(n) – First, we iterate through all n characters of the original text to filter out non-alphanumeric characters and convert everything to lowercase, which takes linear time. Next, we iterate through the clean text to build a reversed copy, taking proportional time based on the number of valid characters remaining, which is at most n. Finally, comparing the clean string and the reversed string character by character requires another linear pass. Adding these sequential steps together results in approximately 3n operations, which simplifies to O(n).
Space Complexity
O(n) – The brute force approach requires building two new strings representing the cleaned text and its reversed copy, where N is the length of the original input string. Each of these newly allocated strings takes up space proportional to the number of valid alphanumeric characters remaining, which is at most N. Therefore, the auxiliary space used by these temporary data structures scales linearly with the input size. Combining these storage requirements leads to an overall auxiliary space complexity of O(n).

Optimal Solution

Approach

Instead of cleaning the entire message and checking it all at once, the optimal approach looks at the text from both ends at the same time and moves inward. By ignoring any symbols or spaces on the fly and comparing the meaningful letters, we can figure out if it reads the same way forward and backward without wasting time or extra space.

Here's how the algorithm would work step-by-step:

  1. Place one finger at the very beginning of the message and another finger at the very end.
  2. Look at the character where your starting finger is resting. If it is a space or a punctuation mark, slide your finger one step further inward to find a real letter.
  3. Look at the character where your ending finger is resting. If it is a space or a punctuation mark, slide your finger one step further inward to find a real letter.
  4. Compare the two letters you found at both fingers, ignoring whether they are uppercase or lowercase.
  5. If the two letters do not match, immediately stop because the message is not a palindrome.
  6. If the two letters do match, slide both fingers one step closer to the middle to check the next pair of letters.
  7. Keep sliding inward and comparing until your fingers meet or cross each other in the middle, confirming the message is a valid palindrome.

Code Implementation

class Solution:
    def isPalindrome(self, input_string: str) -> bool:
        left_pointer = 0
        right_pointer = len(input_string) - 1

        while left_pointer < right_pointer:
            # Skip non-alphanumeric characters from the left to isolate valid letters.
            while left_pointer < right_pointer and not input_string[left_pointer].isalnum():
                left_pointer += 1

            # Skip non-alphanumeric characters from the right to align comparisons.
            while left_pointer < right_pointer and not input_string[right_pointer].isalnum():
                right_pointer -= 1

            # Compare characters case-insensitively to ensure accurate palindrome checking.
            if input_string[left_pointer].lower() != input_string[right_pointer].lower():
                return False

            left_pointer += 1
            right_pointer -= 1

        return True

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the input string. The two-pointer approach moves the start and end pointers inward, visiting each character in the string at most once as they scan toward the center. Since we skip non-alphanumeric characters and compare the remaining characters in a single pass across the string, the number of operations is directly proportional to n. This linear progression of comparisons results in a total of approximately n operations, which simplifies to O(n).
Space Complexity
O(1) – The algorithm relies entirely on a two-pointer approach, maintaining only two integer indices to track the positions at the beginning and the end of the string. It does not allocate any auxiliary data structures, temporary lists, or recursive stack frames regardless of the input size N. Consequently, the extra memory consumed remains constant, leading to an optimal auxiliary space complexity of O(1).

Edge Cases

Empty string or string of length one
How to Handle:
The two pointers start at index zero and string length minus one, safely bypassing the loop and returning true.
String with only non-alphanumeric characters like spaces or punctuation
How to Handle:
Both pointers will continuously skip invalid characters until they cross each other, correctly evaluating as an empty palindrome.
Strings with mixed uppercase and lowercase letters
How to Handle:
Character comparison uses lowercase conversion on both ends to ensure case-insensitivity without altering original data.
Strings containing numbers alongside letters
How to Handle:
Alphanumeric checks correctly include digits and compare them identically to letters.
Very large strings exceeding millions of characters
How to Handle:
The O(n) time and O(1) space two-pointer approach avoids memory overhead and executes efficiently within time limits.
Strings with even versus odd lengths
How to Handle:
The pointer convergence condition stops correctly at the exact middle for both odd and even character counts.
0/75 completed