Valid Palindrome — LeetCode 125 Python Solution

EasyTwo PointersString
Problem
#125
Reading time
2 min

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

Python
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 True

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview