Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 138 · Deep Copy / Multilevel

Copy List with Random Pointer

LeetCode 138 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Interleave copies → set randoms → separate.

మధ్యస్థంHash TableLinked List
LeetCode లో తెరవండి ↗

నేను Copy List with Random Pointer (LeetCode 138) ను ఇలా పరిష్కరించాను — Deep Copy / Multilevel ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Weave a copy of each node right after its original. Then a copy's random pointer is simply original.random.next. Finally unweave the two lists.

Approach

  1. 1

    Insert dup after every node.

  2. 2

    For each original, dup.random = original.random.next.

  3. 3

    Split: link the dups into their own list and restore the originals.

నేను ఎలా పరిష్కరించాను

InterleavingPythonO(n) time · O(1) extra
"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        #put a dup node in between
        node = head
        dummy = Node(-1)
        temp = dummy
        #create dupes
        while node:
            dup = Node(node.val)
            dup.next = node.next
            node.next = dup
            node = node.next.next #go to next original node
        #connect randoms
        node = head
        while node:
            if node.random:
                node.next.random = node.random.next
            node = node.next.next #go to next original node vvip
        #create a chain from dupes
        node = head
        while node:
            next_original = node.next.next
            temp.next = node.next
            temp=temp.next
            node.next = next_original
            node = next_original
        return dummy.next
స్టెప్-త్రూ లోడ్ అవుతోంది…

Copy List with Random Pointer — తరచూ అడిగే ప్రశ్నలు

Copy List with Random Pointer వెనుక ఉన్న intuition ఏమిటి?

Weave a copy of each node right after its original. Then a copy's random pointer is simply original.random.next. Finally unweave the two lists.

Copy List with Random Pointer (LeetCode 138) ను ఎలా పరిష్కరించాలి?

1. Insert dup after every node. 2. For each original, dup.random = original.random.next. 3. Split: link the dups into their own list and restore the originals.

Copy List with Random Pointer యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1) extra. (Accepted approach: Interleaving.)

Copy List with Random Pointer లో సాధారణ పొరపాట్లు ఏమిటి?

Restore the original list's next pointers.