Valid Palindrome — LeetCode 125 Python Solution
- Problem
- #125
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- s = "A man, a plan, a canal: Panama"
- Output
- true
- Explanation
- "amanaplanacanalpanama" is a palindrome.
Python solution
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].lower() != s[j].lower():
return False
else:
i, j = i + 1, j - 1
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 125. Valid Palindrome is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 125. Valid Palindrome?
- LeetCode 125. Valid Palindrome is rated Easy on LeetCode.
- What is the time complexity of LeetCode 125. Valid Palindrome?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 125. Valid Palindrome?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 125. Valid Palindrome cover?
- LeetCode 125. Valid Palindrome is tagged Two Pointers and String on LeetCode.