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.