↓Skip to main content
  1. LeetCode/

LeetCode 125: Valid Palindrome

·2 mins· ·
LeetCode Easy Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-16

  • Submissions: Runtime Error ×2 → Accepted ×2 → Wrong Answer ×2 → Accepted ×8 → Wrong Answer → Accepted ×2

Approach
#

Move two pointers inward (Two Pointers Template 1): each skips characters that are not letters or digits, then compare lowercase forms.

My Attempts
#

In 2022-08 I first wrote “filter with isalnum, lowercase, compare with the reverse”; the first two versions were generator typos (a missing in s, then sif), and fixing them passed. Two later rewrites, a 2022-10 isalpha filter (which also forgot to lowercase) and a 2026 two-pointer version with a hand-written letters-only check, both ignored digits: "1A" compares 1 with a, so the answer is False; it returned True.

Solution
#

class Solution:
    def isPalindrome(self, s: str) -> bool:
        l, r = 0, len(s) - 1
        while l < r:
            if not s[l].isalnum():
                l += 1
            elif not s[r].isalnum():
                r -= 1
            elif s[l].lower() != s[r].lower():
                return False
            else:
                l, r = l + 1, r - 1
        return True

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • The problem says alphanumeric: digits count too, not just letters.

Interview Explanation
#

Two pointers move inward, skipping non-alphanumeric characters and comparing the rest in lowercase; any mismatch means no. Time O(n), space O(1).

Related

LeetCode 28: Find the Index of the First Occurrence in a String
·1 min
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 note: try matching needle at every start, or use str.find; index raises when not found
LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 58: Length of Last Word
·1 min
LeetCode Easy String
LeetCode 58 note: split() with no argument ignores trailing spaces; return the length of the last word
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length