Leetcode 125: Valid Palindrome

grid47
grid47
Exploring patterns and algorithms
Oct 25, 2024 5 min read

A string of letters that glow in perfect symmetry, forming a calm and balanced palindrome.
Solution to LeetCode 125: Valid Palindrome Problem

A string is considered a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include both letters and numbers. Given a string s, return true if it is a palindrome, otherwise return false.
Problem
Approach
Steps
Complexity
Input: The input is a string s that consists of printable ASCII characters.
Example: Input: s = 'Was it a car or a cat I saw?'
Constraints:
• 1 <= s.length <= 2 * 10^5
• s consists only of printable ASCII characters
Output: The output is a boolean value, true if the string is a palindrome, otherwise false.
Example: Output: true
Constraints:
• The string is considered a palindrome if it reads the same when ignoring non-alphanumeric characters and case differences.
Goal: The goal is to check if the given string is a palindrome after ignoring non-alphanumeric characters and converting all letters to lowercase.
Steps:
• Initialize two pointers, one at the start (i = 0) and one at the end (j = s.length() - 1).
• While the two pointers have not crossed each other, check the characters at both pointers.
• If the character at pointer i is not alphanumeric, move i forward.
• If the character at pointer j is not alphanumeric, move j backward.
• If the characters at i and j are equal (ignoring case), move both pointers inward.
• If any character comparison fails, return false.
• If the loop completes without finding any mismatches, return true.
Goal: The constraints ensure that the input string will have at least one character and no more than 200,000 characters.
Steps:
• 1 <= s.length <= 2 * 10^5
• s consists only of printable ASCII characters
Assumptions:
• The string will always contain at least one character.
• We will only work with printable ASCII characters.
Input: Input: s = 'Was it a car or a cat I saw?'
Explanation: After removing non-alphanumeric characters and converting to lowercase, the string becomes 'wasitacaroracatisaw', which is the same forward and backward, so the answer is true.

Input: Input: s = 'race a car'
Explanation: After removing non-alphanumeric characters and converting to lowercase, the string becomes 'raceacar', which is not the same forward and backward, so the answer is false.

Input: Input: s = ' '
Explanation: After removing non-alphanumeric characters, the string becomes an empty string, which is considered a palindrome, so the answer is true.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus