EasyNo. 0125

Valid Palindrome — LeetCode 125 Python Solution

Topics
Two Pointers, String
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

PythonSolution
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

Time
O(n)where n is the length of the string s
Space · auxiliary
O(1)

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

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.

Free to download. Check it runs on your machine, then pick a plan.