Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 86 · Reordering / Partition

Partition List

LeetCode 86 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Two dummy chains, then concatenate.

मध्यमLinked ListTwo Pointers

मी 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. 1

    Two dummies with tails temp1 and temp2.

  2. 2

    Append each node to the matching chain.

  3. 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.next
स्टेप-थ्रू लोड होत आहे…

Partition 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.