Deep Copy Linked List with Random Pointers in O(n) Time

Day - 54 Copy List with Random Pointer The problem - A linked list has next and random pointers. Deep copy the list (create new nodes with same values and pointer relationships). Example : [[7,null],[13,0],[11,4],[10,2],[1,0]] → deep copied list Approach Used - •) Create HashMap<Node, Node> oldToNew. •) Traverse original list (curr = head) 1 - For each node, create new node with same value. 2 - Store mapping, oldToNew.put(curr, new Node(curr.val)). 3 - Move curr forward. •) Traverse original list again (curr = head) 1 - Set next, oldToNew.get(curr).next = oldToNew.get(curr.next). 2 - Set random, oldToNew.get(curr).random = oldToNew.get(curr.random). 3 - Move curr forward. •) Return oldToNew.get(head). Complexity - Time - O(n), two passes. Space - O(n), HashMap stores n mappings. Note - Use HashMap to store old→new node mapping. First pass creates nodes, second pass sets pointers #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories