Advanced list problems
28 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Senior-level linked list questions rarely test a single isolated trick. Instead, they combine dummy nodes, fast-and-slow pointers, in-place reversal, and pointer weaving in O(1) space.
Copy list with random pointer
In Copy List with Random Pointer, every node has val, next and a random pointer to any node or null. We need a deep copy made of n brand-new nodes.
- Pass 1 (Weave clones): Insert each clone
copyright after its original nodecurr(A -> A' -> B -> B' -> C -> C'). Now the clone of any original nodexisx.next. - Pass 2 (Wire
.random): For each original nodecurr, setcurr.next.random = (curr.random != null) ? curr.random.next : null;, then advancecurr = curr.next.next. - Pass 3 (Unweave): Split the woven list back into
A -> B -> CandA' -> B' -> C'.
Example 1 · Brute force: HashMap from each original node to its clone (O(n) time, O(n) extra space)
import java.util.HashMap;import java.util.Map;
public class CopyRandomMapDemo { static class RNode { int val; RNode next, random; RNode(int val) { this.val = val; } }
static RNode copyRandomList(RNode head) { Map<RNode, RNode> clone = new HashMap<>(); for (RNode curr = head; curr != null; curr = curr.next) { clone.put(curr, new RNode(curr.val)); } for (RNode curr = head; curr != null; curr = curr.next) { clone.get(curr).next = clone.get(curr.next); clone.get(curr).random = clone.get(curr.random); } return clone.get(head); }
public static void main(String[] args) { RNode a = new RNode(7), b = new RNode(13), c = new RNode(11); a.next = b; b.next = c; b.random = a; c.random = b; RNode copy = copyRandomList(a); System.out.println("Clone second node: " + copy.next.val + ", random=" + copy.next.random.val); System.out.println("Distinct objects? " + (copy != a && copy.next != b)); }}Clone second node: 13, random=7 Distinct objects? true
What this code does
- Pass 1 creates one clone per original node and stores the pair in the map. Pass 2 uses the map to find the clone of
nextand ofrandom. clone.get(null)returnsnull, so the last node and nodes with norandomneed no special case.- The map holds n pairs, so extra space is O(n). The next example removes the map by weaving each clone right after its original.
Example 2 · Optimal: weave the clones into the list (O(n) time, O(1) extra space)
public class CopyRandomListDemo { static class RNode { int val; RNode next, random; RNode(int val) { this.val = val; } }
public static RNode copyRandomList(RNode head) { if (head == null) return null;
for (RNode curr = head; curr != null; curr = curr.next.next) { RNode copy = new RNode(curr.val); copy.next = curr.next; curr.next = copy; }
for (RNode curr = head; curr != null; curr = curr.next.next) { if (curr.random != null) { curr.next.random = curr.random.next; } }
RNode dummy = new RNode(0), copyTail = dummy; for (RNode curr = head; curr != null; curr = curr.next) { RNode copy = curr.next; curr.next = copy.next; copyTail.next = copy; copyTail = copy; } return dummy.next; }
static String describe(RNode head) { StringBuilder sb = new StringBuilder(); for (RNode c = head; c != null; c = c.next) { String r = (c.random == null) ? "null" : String.valueOf(c.random.val); sb.append("[").append(c.val).append(", rand=").append(r).append("] "); } return sb.toString().trim(); }
public static void main(String[] args) { RNode a = new RNode(7), b = new RNode(13), c = new RNode(11); a.next = b; b.next = c; b.random = a; c.random = b;
RNode clone = copyRandomList(a); System.out.println("Original: " + describe(a)); System.out.println("Clone: " + describe(clone)); System.out.println("Distinct objects? " + (a != clone && b != clone.next)); }}Original: [7, rand=null] [13, rand=7] [11, rand=13] Clone: [7, rand=null] [13, rand=7] [11, rand=13] Distinct objects? true
What this code does
- During Pass 2,
curr.randomis an original node, socurr.random.nextis its newly woven clone. - Pass 3 restores
curr.next = copy.nextso the caller's original list is left unmutated.
One pass fails because A.random may point forward to a node that is not cloned yet. A two-pass HashMap<Node, Node> fixes this in O(n) extra space: pass 1 creates the clones and pass 2 wires next and random.
Can we drop the map and use O(1) extra space? Yes, by weaving each clone node right after its original node.
.random pointers in Pass 2 before unweaving .next pointers in Pass 3. Unweaving restores x.next to the next original node.Intersection of two linked lists
In Intersection of Two Linked Lists, headA and headB may merge at C1. Find the first shared node C1 (pA == pB), or null if disjoint, in O(m + n) time.
Example 3 · Intersection of Two Linked Lists in O(m + n) Time and O(1) Space
public class IntersectionTwoListsDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node getIntersectionNode(Node headA, Node headB) { Node pA = headA; Node pB = headB; while (pA != pB) { pA = (pA == null) ? headB : pA.next; pB = (pB == null) ? headA : pB.next; } return pA; }
public static void main(String[] args) { Node shared = new Node(8, new Node(10, null)); Node headA = new Node(4, new Node(1, shared)); // len 4 (prefix 2) Node headB = new Node(5, new Node(6, new Node(1, shared))); // len 5 (prefix 3) Node disjoint = new Node(99, null);
Node hit = getIntersectionNode(headA, headB); Node miss = getIntersectionNode(headA, disjoint); System.out.println("Intersection of A and B: " + (hit != null ? hit.val : "null")); System.out.println("Intersection with disjoint: " + (miss != null ? miss.val : "null")); }}Intersection of A and B: 8 Intersection with disjoint: null
What this code does
- Both lists have
.val == 1beforeshared, yetgetIntersectionNodecompares object references (pA != pB). - On
headA(len 4) anddisjoint(len 1), both pointers walk 5 steps tonulland returnnull.
When list A and list B have different prefix lengths, pA and pB reach C1 at different steps. To align them, redirect each pointer to the other list's head when it hits null. On the second lap, pA walks a + c + b steps and pB walks b + c + a. Both arrive at C1 together (or both hit null at step a + b if disjoint).
Remember:
- Loop condition:
while (pA != pB)(compares node references with!=). - If they intersect,
pAandpBmeet at the intersection node after at mostm + nsteps. - If disjoint,
pAandpBboth hitnullat stepm + nand the loop returnsnull.
Add two numbers as lists and reorder list
Add Two Numbers adds two numbers stored as lists of digits in reverse order. Reorder List weaves the front half of a list with its reversed back half.
Example 4 · Add Two Numbers and Reorder List (Middle + Reverse + Zip)
public class AddAndReorderDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node addTwoNumbers(Node l1, Node l2) { Node dummy = new Node(0, null), tail = dummy; int carry = 0; while (l1 != null || l2 != null || carry != 0) { int sum = carry + (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0); tail.next = new Node(sum % 10, null); tail = tail.next; carry = sum / 10; if (l1 != null) l1 = l1.next; if (l2 != null) l2 = l2.next; } return dummy.next; }
public static void reorderList(Node head) { if (head == null || head.next == null) return; Node slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } Node prev = null, curr = slow.next; slow.next = null; while (curr != null) { Node nxt = curr.next; curr.next = prev; prev = curr; curr = nxt; } Node p1 = head, p2 = prev; while (p2 != null) { Node n1 = p1.next, n2 = p2.next; p1.next = p2; p2.next = n1; p1 = n1; p2 = n2; } }
static String format(Node h) { StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" -> "); return sb.append("null").toString(); }
public static void main(String[] args) { Node a = new Node(2, new Node(4, new Node(3, null))); Node b = new Node(5, new Node(6, new Node(4, null))); System.out.println("342 + 465: " + format(addTwoNumbers(a, b)));
Node list = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null))))); reorderList(list); System.out.println("Reordered: " + format(list)); }}342 + 465: 7 -> 0 -> 8 -> null Reordered: 1 -> 5 -> 2 -> 4 -> 3 -> null
What this code does
- On
1 -> 2 -> 3 -> 4 -> 5,slowstops at3,4 -> 5reverses to5 -> 4, and zipping gives1 -> 5 -> 2 -> 4 -> 3. - Remember to set
slow.next = null;before zipping so the end of the reordered list does not form a cycle.
In Add Two Numbers, 2 -> 4 -> 3 stands for 342. Loop while (l1 != null || l2 != null || carry != 0) with a dummy tail: add carry plus the current digits, append new Node(sum % 10), and set carry = sum / 10. The || carry != 0 part appends a final node when 99 + 1 = 100.
In Reorder List, change L0 -> L1 -> ... -> Ln in place to L0 -> Ln -> L1 -> Ln-1 -> ... in O(n) time and O(1) space. First find the first middle mid with slow and fast. Second, cut second = mid.next; mid.next = null; and reverse second in place. Third, zip the nodes of head and second alternately.
- Add Two Numbers:
while (l1 != null || l2 != null || carry != 0)handles unequal list lengths and a final carry in one loop. - Reorder List: built from Fast/Slow Middle + In-Place Reverse + Alternating Zip.
Next step
Check your understanding
10 quick questions