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.