neetcode-gh/leetcode

validPalindrome solution is unnecessarily O(n) memory and doesn't use 2 pointers

Opened this issue · 0 comments

Current solution on neetcode.io:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        new = ''
        for a in s:
            if a.isalpha() or a.isdigit():
                new += a.lower()
        return (new == new[::-1])

This feels silly, especially when it's marked as a two pointers problem. I feel like this will confuse beginners and lead people astray. Pretty much every two pointers problem follows the same pattern of some sort of while l < r. There's no reason to break this with a worse solution.

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