Valid Palindrome
LeetCode 125 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Two pointers that skip non-alphanumerics.
मैंने Valid Palindrome (LeetCode 125) ऐसे हल किया — Two Pointers पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Compare characters from both ends, skipping anything that isn't a letter or digit and ignoring case. Any mismatch means it's not a palindrome.
Approach
- 1
left at 0, right at the end.
- 2
Move each pointer past non-alphanumeric characters.
- 3
Compare lower-cased characters; mismatch → False.
- 4
Step both inward until they meet.
मैंने कैसे हल किया
Two pointersPythonO(n) time · O(1) space
class Solution:
def isPalindrome(self, s: str) -> bool:
left=0
right=len(s)-1
while left<right:
while left<right and not s[left].isalnum():
left+=1
while left<right and not s[right].isalnum():
right-=1
if s[left].lower()!=s[right].lower():
return False
left+=1
right-=1
return True
Valid Palindrome — अक्सर पूछे जाने वाले प्रश्न
Valid Palindrome के पीछे intuition क्या है?
Compare characters from both ends, skipping anything that isn't a letter or digit and ignoring case. Any mismatch means it's not a palindrome.
Valid Palindrome (LeetCode 125) कैसे हल करें?
1. left at 0, right at the end. 2. Move each pointer past non-alphanumeric characters. 3. Compare lower-cased characters; mismatch → False. 4. Step both inward until they meet.
Valid Palindrome की time और space complexity क्या है?
Time: O(n)। Space: O(1)। (Accepted approach: Two pointers।)
Valid Palindrome में आम गलतियाँ क्या हैं?
Keep the left < right guard inside the skip loops so they can't cross.