Skip to content

Latest commit

 

History

History
45 lines (32 loc) · 1.52 KB

File metadata and controls

45 lines (32 loc) · 1.52 KB

Level: Medium

Topic: Hash Table Linked List

Question

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]

Intuition

  • Use hashmap to create old node corresponds to the new nodes
  • copy every node to the map with the old node
  • iterate the list again to connect all next node and random nodes

Code

Time: O(n)
Space: O(n)

public Node copyRandomList(Node head) {
    HashMap<Node, Node> map = new HashMap<>();
    Node curr = head;

    while (curr != null) {
        map.put(curr, new Node(curr.val));
        curr = curr.next;
    }

    curr = head;
    while (curr != null) {
        Node newNode = map.get(curr);
        newNode.next = map.get(curr.next);
        newNode.random = map.get(curr.random);
        curr = curr.next;
    }

    return map.get(head);
}