DSA – Linked List Quick Recap

dsa quick recap
138. Copy List with Random Pointer 

//⭐ Version 1 — HashMap Method (Simple & Clear)
//⏱ Time: O(n)
// 💾 Space: O(n)

function copyRandomList_O1(head: Node | null): Node | null {
    if (head === null) return null;
    let curr: Node | null = head;

    // 1️⃣ Clone nodes and insert them between original nodes
    while (curr) {
        const copy = new Node(curr.val);
        copy.next = curr.next;
        curr.next = copy;
        curr = copy.next;
    }

    // 2️⃣ Assign random pointers for the copies
    curr = head;
    while (curr) {
        if (curr.random) {
            curr.next!.random = curr.random.next;
        }
        curr = curr.next!.next;
    }

    // 3️⃣ Separate the original list and the copied list
    curr = head;
    const newHead = head.next;
    while (curr) {
        const copy = curr.next!;
        curr.next = copy.next;
        copy.next = copy.next ? copy.next.next : null;
        curr = curr.next;
    }
    return newHead;
}

// ⭐ Version 2 — Interweaving Method (Optimal O(1) space)
// ⏱ Time: O(n)
// 💾 Space: O(1)

function copyRandomList_O1(head: Node | null): Node | null {
    if (head === null) return null;
    let curr: Node | null = head;

    // 1️⃣ Clone nodes and insert them between original nodes
    while (curr) {
        const copy = new Node(curr.val);
        copy.next = curr.next;
        curr.next = copy;
        curr = copy.next;
    }

    // 2️⃣ Assign random pointers for the copies
    curr = head;
    while (curr) {
        if (curr.random) {
            curr.next!.random = curr.random.next;
        }
        curr = curr.next!.next;
    }

    // 3️⃣ Separate the original list and the copied list
    curr = head;
    const newHead = head.next;
    while (curr) {
        const copy = curr.next!;
        curr.next = copy.next;
        copy.next = copy.next ? copy.next.next : null;
        curr = curr.next;
    }
    return newHead;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top