Leetcode Problem 125: Valid Palindrome

Problem description:

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.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1: 

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric 
characters. Since an empty string reads the same forward and backward,
it is a palindrome.

Constraints:

  • 1 <= s.length <= 2 * $ 10^5 $
  • s consists only of printable ASCII characters.

Python solution Link to heading


# leetcode_125.py

class Solution:
    def isPalindrome(self, s: str) -> bool:
        if len(s) == 1:
            return True
        alnum_s = "".join(char.lower() for char in s if char.isalnum())
        if alnum_s == "".join(reversed(alnum_s)):
            return True
        return False
Python statistics Link to heading
Runtime: 58 ms - beats 66.66% of python3 submissions.
Memory Usage: 19.3 MB - beats 8.89% of python3 submissions.
Complexity analysis Link to heading
  • Time: $ O(n) $, because the reversed() function traverses the alphanumeric version of the input string entirely, every time. The other $ O(n) $ operation is found in the forloop above it, but that runs slightly faster because not all iterations are expensive, only the ones where the char is alphanumeric.

  • Space: $ O(n + n) = 2 ~ O(n) = O(n)$ because we create two string of size $ n $, the input string filtered for alphanumeric characters only, and the reverse of that. This is inefficient, which makes me believe the optimal solution involves clever referencing, aka pointers.



Share on:
LinkedIn