Copy List with Random Pointer
LeetCode 138 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Interleave copies → set randoms → separate.
நான் 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
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.
நான் எப்படித் தீர்த்தேன்
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.