Partition List
LeetCode 86 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Two dummy chains, then concatenate.
मैंने Partition List (LeetCode 86) ऐसे हल किया — Reordering / Partition पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Build two separate chains while walking once: nodes smaller than x and the rest. Then join the first chain's tail to the second chain's head. Relative order inside each chain is preserved.
Approach
- 1
Two dummies with tails temp1 and temp2.
- 2
Append each node to the matching chain.
- 3
temp1.next = second chain; terminate the second chain.
मैंने कैसे हल किया
Two chainsPythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
DummyNode1,DummyNode2 = ListNode(),ListNode()
temp1= DummyNode1
temp2=DummyNode2
node = head
while node:
if node.val<x:
temp1.next=node
temp1 = temp1.next
else:
temp2.next = node
temp2 = temp2.next
node = node.next
temp1.next = DummyNode2.next
temp2.next = None
return DummyNode1.nextPartition List — अक्सर पूछे जाने वाले प्रश्न
Partition List के पीछे intuition क्या है?
Build two separate chains while walking once: nodes smaller than x and the rest. Then join the first chain's tail to the second chain's head. Relative order inside each chain is preserved.
Partition List (LeetCode 86) कैसे हल करें?
1. Two dummies with tails temp1 and temp2. 2. Append each node to the matching chain. 3. temp1.next = second chain; terminate the second chain.
Partition List की time और space complexity क्या है?
Time: O(n)। Space: O(1)। (Accepted approach: Two chains।)
Partition List में आम गलतियाँ क्या हैं?
Set temp2.next = None or the list may loop.