Problem
Return true if a string is a palindrome after converting letters to lowercase and removing every character that is not a letter or a digit.
Original: LeetCode 125: Valid Palindrome.
Examples
Example 1
`s = "A man, a plan, a canal: Panama"``true`After removing non-alphanumeric characters and lowercasing, it reads "amanaplanacanalpanama".
Example 2
`s = "race a car"``false`Example 3
`s = " "``true`Nothing is left after filtering, and an empty string is a palindrome.
Constraints
1 <= s.length <= 2 * 10^5sconsists only of printable ASCII characters.
Hints
Hint 1
Spaces, punctuation and letter case do not count. An empty string, or a string that becomes empty after filtering, is a palindrome.
Hint 2
Comparing characters from the outside in is the opposite-ends two-pointer pattern.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Build a filtered lowercase string, then check whether it equals its reverse. That uses extra linear space.
Optimal. Keep a left and a right index on the original string. Advance each one until it points at an alphanumeric character, compare the two in lowercase, and move inward.
Alternative. A regex clean-up plus a reverse is shorter to type and still linear, but it allocates a second string.
Complexity
- Time
- O(n)
O(n) time, O(1) extra space.
- Space
- O(1)
Code
def is_palindrome(s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return False
i += 1
j -= 1
return True
if __name__ == "__main__":
assert is_palindrome("A man, a plan, a canal: Panama") is True
assert is_palindrome("race a car") is False
assert is_palindrome(" ") is True
print("ok")public class ValidPalindrome {
static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false;
i++;
j--;
}
return true;
}
public static void main(String[] args) {
if (!isPalindrome("A man, a plan, a canal: Panama")) throw new AssertionError();
if (isPalindrome("race a car")) throw new AssertionError();
if (!isPalindrome(" ")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "A man, a plan, a canal: Panama" is true, "race a car" is false, and " " is true.
- A string with only punctuation is true, because nothing remains to compare.
Follow-ups
- Valid Palindrome II asks whether you can delete at most one character and still have a palindrome.
Interview script
"I do not build a cleaned copy. Two pointers skip non-alphanumeric characters and compare lowercase letters from both ends, so I use linear time and constant extra space."
Source: LeetCode 125: Valid Palindrome Source: Java SE 17 API: Character.isLetterOrDigit)
Same-direction read/write pointers
Sources (2)
- LeetCode 125: Valid Palindromeleetcode.com
- Java SE 17 API: Character.isLetterOrDigitdocs.oracle.com