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 * 105s consists only of printable ASCII characters.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:
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:
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_charactersInstead 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:
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| Case | How to Handle |
|---|---|
| Empty string or string of length one | 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 | 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 | Character comparison uses lowercase conversion on both ends to ensure case-insensitivity without altering original data. |
| Strings containing numbers alongside letters | Alphanumeric checks correctly include digits and compare them identically to letters. |
| Very large strings exceeding millions of characters | 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 | The pointer convergence condition stops correctly at the exact middle for both odd and even character counts. |