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.