Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 680 · Two Pointers

Valid Palindrome II

LeetCode 680 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

On the first mismatch, try both deletions once.

सोपाTwo PointersStringGreedy

मी Valid Palindrome II (LeetCode 680) असा सोडवला — Two Pointers पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Walk inward from both ends. At the first mismatch you get one deletion: try skipping the left character or the right character, and check whether what remains between the pointers is a palindrome.

Approach

  1. 1

    Two pointers from the ends.

  2. 2

    Matching characters: move inward.

  3. 3

    Mismatch: return palindrome(i+1, j) or palindrome(i, j−1).

मी कसा सोडवला

Two pointers + one skipPythonO(n) time · O(1) space
class Solution:
    def check_palindrome(self,i,j,s) ->bool:
        while i<j:
            if s[i]!=s[j]:
                return False
            i+=1
            j-=1        
        return True

    def validPalindrome(self, s: str) -> bool:
        i,j=0,len(s)-1
        while(i<j):
            #Found a mismatched pair, try both deletions
            if s[i]!=s[j]:
                return self.check_palindrome(i+1,j,s) or self.check_palindrome(i,j-1,s)
            i=i+1
            j=j-1
        return True
स्टेप-थ्रू लोड होत आहे…

Valid Palindrome II — वारंवार विचारले जाणारे प्रश्न

Valid Palindrome II मागील intuition काय आहे?

Walk inward from both ends. At the first mismatch you get one deletion: try skipping the left character or the right character, and check whether what remains between the pointers is a palindrome.

Valid Palindrome II (LeetCode 680) कसा सोडवावा?

1. Two pointers from the ends. 2. Matching characters: move inward. 3. Mismatch: return palindrome(i+1, j) or palindrome(i, j−1).

Valid Palindrome II ची time आणि space complexity किती आहे?

Time: O(n). Space: O(1). (Accepted approach: Two pointers + one skip.)

Valid Palindrome II मध्ये सामान्य चुका कोणत्या?

Only one deletion is allowed — don't recurse with another deletion budget.