Tensorum
YouTubeसीखना शुरू करें
LeetCode 138 · Deep Copy / Multilevel

Copy List with Random Pointer

LeetCode 138 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Interleave copies → set randoms → separate.

मध्यमHash TableLinked List

मैंने 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.