JavaScript O(n) solution using ES6 Map


  • 0
    var copyRandomList = function(head) {
        if (!head) return null;
        const dummy = new RandomListNode();
        const map = new Map();
        
        let src = head;
        let dest = dummy;
        while (src && !map.has(src)) {
            dest.next = new RandomListNode(src.label);
            map.set(src, dest.next);
            src = src.next;
            dest = dest.next;
        }
        
        for (let [src, dest] of map) {
            dest.random = map.get(src.random) || null;
        }
        
        return dummy.next;
    };
    

    Map allows us to key by node reference. This should also work for lists that cycle.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.