Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 86 · Reordering / Partition

Partition List

LeetCode 86 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Two dummy chains, then concatenate.

நடுத்தரம்Linked ListTwo Pointers
LeetCode இல் திற ↗

நான் 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.