Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
samlevine03 opened this issue Oct 21, 2024 · 0 comments

Comments

@samlevine03
Copy link

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
@samlevine03 samlevine03 changed the title validPalindrome solution is unnecessarily O(n) memory validPalindrome solution is unnecessarily O(n) memory and doesn't use 2 pointers Oct 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant