Palindrome Linked List
LeetCode 234 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Middle → reverse second half → compare.
मैंने Palindrome Linked List (LeetCode 234) ऐसे हल किया — Palindrome पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Find the middle with slow/fast pointers, reverse the second half, and compare it against the first half node by node. Reverse it back afterwards to leave the list unchanged.
Approach
- 1
Slow/fast to find the middle.
- 2
Reverse from slow to the end.
- 3
Walk both halves comparing values.
- 4
Reverse the second half back.
मैंने कैसे हल किया
Reverse second halfPythonO(n) time · O(1) space
class Solution:
def reverseList(self, temp):
prev = None
while temp is not None:
front = temp.next
temp.next = prev
prev = temp
temp = front
return prev
def isPalindrome(self, head):
if head is None:
return False
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
p1 = head
slow = self.reverseList(slow)
p2 = slow
is_palindrome = True
while p1 is not None and p2 is not None:
if p1.val != p2.val:
is_palindrome = False
p1 = p1.next
p2 = p2.next
slow = self.reverseList(slow)
return is_palindromePalindrome Linked List — अक्सर पूछे जाने वाले प्रश्न
Palindrome Linked List के पीछे intuition क्या है?
Find the middle with slow/fast pointers, reverse the second half, and compare it against the first half node by node. Reverse it back afterwards to leave the list unchanged.
Palindrome Linked List (LeetCode 234) कैसे हल करें?
1. Slow/fast to find the middle. 2. Reverse from slow to the end. 3. Walk both halves comparing values. 4. Reverse the second half back.
Palindrome Linked List की time और space complexity क्या है?
Time: O(n)। Space: O(1)। (Accepted approach: Reverse second half।)
Palindrome Linked List में आम गलतियाँ क्या हैं?
Restoring the list is good practice — callers may reuse it.