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)) {
   = new RandomListNode(src.label);
            src =;
            dest =;
        for (let [src, dest] of map) {
            dest.random = map.get(src.random) || null;

    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.