LeetCode Collections: Interview Problems from Naive to Optimal / Module 06

Module 6: Linked Lists

Work seven linked list problems as spoken interviews, from reversing a list to an O(1) LRU cache and merging k sorted lists with a heap.

Here is a first answer to 141. Linked List Cycle: walk the list and remember every node you pass. If you meet a node twice, the list loops.

// Remember every node we pass; reaching one we have seen means the list loops.
// Time O(n): each node is visited once. Memory O(n): the set holds up to n nodes.
export function hasCycleSet(head: ListNode | null): boolean {
  const seen = new Set<ListNode>();
  for (let node = head; node !== null; node = node.next) {
    if (seen.has(node)) return true;
    seen.add(node);
  }
  return false;
}

LeetCode allows up to 10⁴ nodes, so this answer fits easily. At 10⁵ nodes it took 2.77 ms in the measurement at the end of this page. But the problem’s page asks, as a follow-up, for O(1) memory, and the set held 21.0 bytes per node, 21 MB at 10⁶ nodes. Two pointers that move at different speeds answer it with two variables, and they were 10 to 16 times faster too.

This module works seven problems on linked lists, where the answer is a few pointers moved in the right order. Each one follows the nine steps from Module 1, from the naive solution to the optimal one.

After this module, you can:

  • relink a list in place with a few pointers, and use a dummy node so the first node needs no special case
  • find a cycle, a middle node or the n-th node from the end with two pointers that move at different speeds or a fixed gap apart, in O(1) memory
  • combine steps you already trust (find the middle, reverse, merge) into one O(n) answer
  • build an LRU cache with O(1) get and put from a Map and a doubly linked list, and say why a Map alone isn’t O(1) in V8
  • merge k sorted lists in O(N log k) with a min-heap of their first nodes

The code for this module is in module-06/ of the course repository, and node --test "module-06/**/*.test.ts" from its root runs every test. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.

The pattern: move a few pointers, never search

A linked list is a sequence where each item, a node, holds a value and a pointer to the next node. The first node is the head, and the last node, the tail, points to null. DSA Module 4 teaches it. LeetCode gives every list problem the same node class, and the lab defines it in shared/list-node.ts:

// LeetCode's ListNode, with the same fields and constructor as its TypeScript template.
export class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val?: number, next?: ListNode | null) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}

LeetCode declares ListNode for you, so paste each solution without the lab file’s import line.

A list has no index. Reaching the k-th node walks k links, so any answer that looks for a node by position pays O(n) each time. The fast answers in this module never look for a node. They keep a pointer on each node they will need next, and change a few next fields per step.

Signs that point to this pattern:

  • the input is a ListNode, and the page asks you to relink nodes, not copy values
  • “in one pass” or “in O(1) memory” on a list
  • a position counted from the end, or the middle of a list whose length you don’t know
  • a cache that must find a key and also move it to the front in O(1)

The cost is the bookkeeping. Each step changes two or three links, and the order of those writes matters: overwrite a next before you save it, and the rest of the list is gone.

Rule: On a linked list, keep a pointer on every node you’ll need next, and save a next before you overwrite it.

206. Reverse Linked List

206. Reverse Linked List is rated Easy. You get the head of a list. Turn the list around, so the last node comes first and every link points back to the node that used to come before it, and return the new head.

  • 0 ≤ n ≤ 5000 nodes
  • -5000 ≤ val ≤ 5000
  • the page’s follow-up: write it both with a loop and with recursion

The signature is function reverseList(head: ListNode | null): ListNode | null. Try it on LeetCode first.

Hint

When you turn one node’s arrow around, you lose your way to the next node. What must you save first?

Interviewer: Reverse this list, and return its new head.

Candidate: So the last node becomes the head, and every next points to the node that came before it. Can the list be empty?

Interviewer: Yes, it can have no nodes.

Candidate: Then I return null. Should I build a new list, or change the links of the nodes I get?

Interviewer: Changing the links is fine.

Candidate: How long can it be?

Interviewer: Up to 5,000 nodes.

The interviewer and the candidate are invented. The problems, limits and timings are real.

Candidate: Here’s my example, an undo history with the newest action last, and three edge cases.

list              expected
[10, 20, 30, 40]  [40, 30, 20, 10]
[]                []                empty: return null
[7]               [7]               one node, its next stays null
[4, 9]            [9, 4]            the old head must end with next = null

Candidate: The naive solution copies the nodes into an array, then links them again from the back.

// Put every node in an array, then link them again from the back.
// Time O(n): two passes. Memory O(n): the array holds every node.
export function reverseListByArray(head: ListNode | null): ListNode | null {
  const nodes: ListNode[] = [];
  for (let node = head; node !== null; node = node.next) nodes.push(node);
  for (let i = nodes.length - 1; i > 0; i--) nodes[i].next = nodes[i - 1];
  if (nodes.length > 0) nodes[0].next = null;
  return nodes.length > 0 ? nodes[nodes.length - 1] : null;
}

Candidate: That’s O(n) time, two passes, and O(n) memory for the array. At 5,000 nodes it’s about 10⁴ steps, so it fits easily.

Interviewer: Can you do it without the array?

Candidate: The array only remembers every node’s place while I change the links. But walking forward, I only ever need three nodes: the one before, the current one, and the one after it.

Candidate: So I keep prev and node. At each step I save node.next, point node back at prev, and move both forward.

Changing the links of the nodes you were given, with no copy, is working in place. It’s what makes O(1) memory possible on a list.

// Walk once and turn each arrow around; save next before overwriting it.
// Time O(n): one pass. Memory O(1): three pointers.
function reverseList(head: ListNode | null): ListNode | null {
  let prev: ListNode | null = null;
  let node = head;
  while (node !== null) {
    const next = node.next;
    node.next = prev;
    prev = node;
    node = next;
  }
  return prev;
}

export { reverseList };

Candidate: After each step, the nodes I’ve passed form a reversed list that starts at prev. When node reaches null, prev is the new head.

Interviewer: Trace your example.

Figure 1 shows the list after step 2, then every step of the loop on [10, 20, 30, 40].

after step 2   null <- [10] <- [20]    [30] -> [40] -> null
                                ^       ^
                               prev    node

step  next saved  node.next = prev  prev  node  reversed so far
1     [20]        [10] -> null      [10]  [20]  10
2     [30]        [20] -> [10]      [20]  [30]  20 10
3     [40]        [30] -> [20]      [30]  [40]  30 20 10
4     null        [40] -> [30]      [40]  null  40 30 20 10

Figure 1: each step turns one arrow, and the saved next is the only way back to the rest of the list.

Candidate: For [7], the loop runs once: [7].next becomes null, and I return [7]. For an empty list, the loop doesn’t run, and I return prev, which is null.

Interviewer: Final cost?

Candidate: O(n) time: one pass. O(1) memory: three pointers.

The naive answer and the loop take the same O(n) time. What the loop removes is the O(n) memory.

Interviewer: The page also asks for a recursive version.

The Candidate’s answer

Candidate: I reverse the rest of the list first. Then the old head.next is the tail of the reversed rest, so I hang head after it and cut head.next.

// Reverse the rest of the list, then hang the current node after its old next node.
// Time O(n): one call per node. Memory O(n): one stack frame per node.
export function reverseListRecursive(head: ListNode | null): ListNode | null {
  if (head === null || head.next === null) return head;
  const newHead = reverseListRecursive(head.next);
  head.next.next = head; // the old next node is now the tail of the reversed rest
  head.next = null;
  return newHead;
}

Candidate: It’s O(n) time, but O(n) memory, because each node keeps one call waiting on the call stack. At 5,000 nodes that fits, but a longer list would overflow it.

atlimit.ts in the module folder times one call of a solution at LeetCode’s limit, so its numbers are rough. There, reverseListRecursive reversed 5,000 nodes in 1.4 ms. On 100,000 nodes it threw RangeError: Maximum call stack size exceeded, and a binary search on the length found 8,885 nodes as the longest it handled in that run. Module 4 explains the call stack: one frame per call that hasn’t returned, in a space whose size V8 caps.

Interviewer: What if I ask you to reverse only the nodes from position m to position n?

The Candidate’s answer

Candidate: I walk to the node before position m and keep it. Then I run the same loop for n − m + 1 nodes. At the end I link the node before m to the new first node of the part, and the old first node of the part to the node after n. It’s still O(n) time and O(1) memory.

That’s LeetCode’s 92. Reverse Linked List II, which this course doesn’t cover. This version isn’t in the lab.

Two mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module that has one.

  • Returning head instead of prev. After the loop, the old head is the tail. [1, 2, 3] returns [1] instead of [3, 2, 1]. Return prev.
  • Writing node.next = prev before saving node.next. That write deletes the only link to the rest of the list, so the loop stops after one node. Save next first.

Lab folder: module-06/0206-reverse-linked-list/ in the course repository.

21. Merge Two Sorted Lists

21. Merge Two Sorted Lists is rated Easy. You get two lists, each sorted from small to large. Join their nodes into one sorted list, reusing the nodes instead of making new ones, and return its head.

  • each list has 0 to 50 nodes
  • -100 ≤ val ≤ 100
  • both lists are sorted in non-decreasing order
  • the result must be made of the nodes of the two lists

The signature is function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null. Try it on LeetCode first.

Hint

Only two nodes can be the smallest one left. Which two?

Interviewer: Merge these two sorted lists into one.

Candidate: Can either list be empty?

Interviewer: Yes, or both.

Candidate: Then I return the other one, or null. Can values repeat, inside a list or across both?

Interviewer: Yes.

Candidate: Do I make new nodes, or relink the ones I get?

Interviewer: Relink them.

Candidate: Here’s my example, two lists of delivery times, and two edge cases.

list1         list2              expected
[2, 6, 9]     [3, 4, 10, 12]     [2, 3, 4, 6, 9, 10, 12]
[5]           []                 [5]               one list empty
[1, 2, 3]     [7, 8]             [1, 2, 3, 7, 8]   one ends before the
                                                   other starts

Candidate: The naive solution puts every node in an array, sorts it by value, and links the nodes in that order.

// Put the nodes of both lists in one array, sort it by value, and link the nodes in that order.
// Time O((n + m) log(n + m)): the sort ignores that both lists are already sorted. Memory O(n + m): the array.
export function mergeTwoListsBySort(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  const nodes: ListNode[] = [];
  for (let node = list1; node !== null; node = node.next) nodes.push(node);
  for (let node = list2; node !== null; node = node.next) nodes.push(node);
  nodes.sort((a, b) => a.val - b.val);
  for (let i = 0; i < nodes.length - 1; i++) nodes[i].next = nodes[i + 1];
  if (nodes.length > 0) nodes[nodes.length - 1].next = null;
  return nodes.length > 0 ? nodes[0] : null;
}

Candidate: That’s O((n + m) log(n + m)) time for the sort, and O(n + m) memory for the array. At 100 nodes in all, it fits easily.

Interviewer: The lists are already sorted. Can you use that?

Candidate: The sort compares nodes whose order the lists already give. The smallest node left is always one of the two heads, so I compare only those two, attach the smaller one, and move that list forward.

Candidate: The first node attached has nothing before it, so it would need its own branch. I start the result with a dummy node instead, and return what comes after it.

A dummy node is a placeholder node before the first real node. The code that attaches a node then always has a node to attach it to, and you return dummy.next.

// A dummy node before the result, so the first node needs no special case; attach the smaller head each step.
// Time O(n + m): each node is attached once. Memory O(1): only pointers are relinked.
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  const dummy = new ListNode();
  let tail = dummy;
  while (list1 !== null && list2 !== null) {
    if (list1.val <= list2.val) {
      tail.next = list1;
      list1 = list1.next;
    } else {
      tail.next = list2;
      list2 = list2.next;
    }
    tail = tail.next;
  }
  tail.next = list1 !== null ? list1 : list2; // one list may still have nodes, already sorted
  return dummy.next;
}

export { mergeTwoLists };

Candidate: When one list runs out, the rest of the other is already sorted, and every value in it is at least the last one I attached. So one link attaches all of it.

Interviewer: Trace your example.

Figure 2 traces the merge of [2, 6, 9] and [3, 4, 10, 12]. The two list columns show each list’s head before the step.

step  list1  list2  attach  result after dummy
1     [2]    [3]    [2]     2
2     [6]    [3]    [3]     2 3
3     [6]    [4]    [4]     2 3 4
4     [6]    [10]   [6]     2 3 4 6
5     [9]    [10]   [9]     2 3 4 6 9
end   null   [10]   rest    2 3 4 6 9 10 12

Figure 2: each step compares only the two heads, and the leftover list joins in one link at the end.

Candidate: For [5] and [], the loop doesn’t run, and tail.next becomes [5]. For [1, 2, 3] and [7, 8], three steps take 1, 2 and 3, and then [7, 8] is attached whole.

Interviewer: Final cost?

Candidate: O(n + m) time: each node is attached once. O(1) memory: the dummy node and two pointers.

Interviewer: Would you write it recursively?

The Candidate’s answer

Candidate: The smaller head comes first, and its next is the merge of what’s left. That’s short:

// The smaller head comes first; the rest is the merge of what is left.
// Time O(n + m): one call per node. Memory O(n + m): one stack frame per node.
export function mergeTwoListsRecursive(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  if (list1 === null) return list2;
  if (list2 === null) return list1;
  if (list1.val <= list2.val) {
    list1.next = mergeTwoListsRecursive(list1.next, list2);
    return list1;
  }
  list2.next = mergeTwoListsRecursive(list1, list2.next);
  return list2;
}

Candidate: At 100 nodes it’s safe. But it keeps one frame per node, so long lists would hit the same call stack limit as 206’s recursion. The loop has no limit and uses O(1) memory, so I’d write the loop.

Interviewer: Two nodes have the same value. Which one comes first?

The Candidate’s answer

Candidate: The one from list1, because I take from list1 when list1.val <= list2.val. With <, ties would come from list2 first. Both are sorted, but <= keeps equal values in the order of the inputs.

Interviewer: And if there were k lists?

The Candidate’s answer

Candidate: Then the smallest node left is one of k heads, and comparing all k at every step costs O(k) per node. That’s 23. Merge k Sorted Lists, the last problem in this module.

One mistake is common here:

  • Not attaching the rest when one list runs out. The loop stops as soon as either list is empty, so the other list’s last nodes are dropped. [1, 3, 5] and [2] return [1, 2] instead of [1, 2, 3, 5]. After the loop, link tail.next to whichever list is left.

Lab folder: module-06/0021-merge-two-sorted-lists/ in the course repository.

141. Linked List Cycle

141. Linked List Cycle is rated Easy. You get the head of a list whose tail may point back to an earlier node instead of null. Return whether following next from the head ever reaches a node a second time.

  • 0 ≤ n ≤ 10^4 nodes
  • -10^5 ≤ val ≤ 10^5
  • LeetCode builds the loop from a position it doesn’t pass to your function
  • the page’s follow-up: solve it with O(1) memory

The signature is function hasCycle(head: ListNode | null): boolean. Try it on LeetCode first.

Hint

Two runners on a circular track, one twice as fast as the other. Does the fast one pass the slow one, or land on it?

Interviewer: Tell me whether this list loops.

Candidate: A list loops when some node’s next points back to a node I’ve already passed. Do I get the position where the tail links back?

Interviewer: No, only the head.

Candidate: Can the list be empty?

Interviewer: Yes. That’s no loop.

Candidate: Can values repeat?

Interviewer: Yes.

Candidate: Then equal values don’t mean a loop. I compare nodes, not values. May I change the nodes, for example to mark the ones I’ve seen?

Interviewer: No.

A cycle in a list is a loop: following next from some node leads back to it, so a walk from the head never reaches null.

Candidate: Here’s my example, a chain of web redirects, and three edge cases.

list                                        expected
/a -> /b -> /c -> /d -> back to /b          true
/a -> /b -> /c -> /d -> null                false   the same pages, no loop
[5] -> back to itself                       true    one node
[7, 7, 7], no loop                          false   equal values only

Candidate: The naive solution remembers every node in a Set. The first node I meet twice proves a loop, and reaching null proves there is none.

The Candidate writes hasCycleSet, the function at the top of this page.

Candidate: It’s O(n) time and O(n) memory for the set. At 10⁴ nodes it fits easily.

Interviewer: The page asks for O(1) memory. Can you do that?

Candidate: The set remembers every node so that it can recognize one. But I don’t need to recognize a node. I only need to know the walk never ends.

Candidate: So I send two pointers down the list, slow one node per step and fast two. Without a loop, fast reaches null. With a loop, both end up inside it, and fast catches up with slow.

Candidate: It can’t jump over slow. Once both are in the loop, the distance from fast forward to slow shrinks by exactly one node per step, so it reaches 0 within one lap.

Fast and slow pointers are two pointers that walk the same list at different speeds, here two nodes and one node per step. Finding a cycle this way is usually credited to Robert W. Floyd, and DSA Module 4 works through it.

// Floyd's two pointers: fast moves two nodes per step, slow one. In a loop fast gains one node per step, so it lands on slow.
// Time O(n): fast reaches the end, or catches slow within one lap of the loop. Memory O(1): two pointers.
function hasCycle(head: ListNode | null): boolean {
  let slow = head;
  let fast = head;
  while (fast !== null && fast.next !== null) {
    slow = slow!.next;
    fast = fast.next.next;
    if (slow === fast) return true;
  }
  return false;
}

export { hasCycle };

Candidate: The loop checks fast and fast.next before it moves fast two nodes. So fast.next.next never reads past null.

Pause and predict. On the redirect example with the loop, at which step do slow and fast meet, and on which page?

Interviewer: Trace your example.

Figure 3 traces it. The loop is /b, /c, /d, three pages long.

[/a] -> [/b] -> [/c] -> [/d] -> back to [/b]

step  slow  fast  fast to slow, along the loop
0     /a    /a    both start at the head
1     /b    /c    2 nodes (/c -> /d -> /b)
2     /c    /b    1 node  (fast went /c -> /d -> /b)
3     /d    /d    0: slow === fast, return true

Figure 3: once both pointers are in the loop, the gap between them shrinks by one node per step, so they meet within one lap.

Candidate: Without the loop, step 1 puts slow on /b and fast on /c, and step 2 moves fast past /d to null. The loop ends, and I return false.

Interviewer: Final cost?

Candidate: O(n) time. Without a loop, fast reaches the end in n/2 steps. With one, slow enters it within n steps, and they meet within one more lap, which is at most n nodes. O(1) memory: two pointers.

The measurement at the end of this page times both answers on lists of up to 4 × 10⁶ nodes.

Interviewer: Can you return the node where the loop starts?

The Candidate’s answer

Candidate: Yes. When they meet, slow has walked s steps and fast 2s, so the extra s steps are whole laps of the loop. I put one pointer back on the head and step both by one node. Say the loop starts μ nodes from the head. After μ steps, the first pointer is at the loop’s start. The second has then walked s + μ steps from the head in all, which is μ steps plus whole laps, so it’s there too.

Candidate: The first node where they meet is the start of the loop. It’s still O(n) time and O(1) memory.

That’s LeetCode’s 142. Linked List Cycle II, which this course doesn’t cover. This version isn’t in the lab.

Interviewer: How long is the loop?

The Candidate’s answer

Candidate: After they meet, I keep one pointer still and step the other until it comes back, counting the steps. The count is the loop’s length.

Interviewer: The list has at most 10⁴ nodes. Why not walk 10⁴ + 1 steps, and say “loop” if you haven’t reached null?

The Candidate’s answer

Candidate: It works for this page, because the limit is known. But it’s O(limit), not O(n), and it breaks the day the limit changes. I’d mention it, then give the two pointers.

Two mistakes are common here:

  • Comparing before moving. Both pointers start on the head, so slow === fast is true at once. [1, 2, 3] with no loop returns true instead of false. Move both pointers first, then compare.
  • Checking only fast.next. On a list of even length, fast lands on null itself. [1, 2, 3, 4] with no loop throws TypeError: Cannot read properties of null (reading 'next') instead of returning false. Check fast !== null && fast.next !== null.

Lab folder: module-06/0141-linked-list-cycle/ in the course repository.

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List is rated Medium. You get a list and a number n. Remove the node that is n-th when you count from the end, so the last node is the 1st. Return the head of what is left, which changes if you removed the head.

  • 1 ≤ sz ≤ 30 nodes
  • 0 ≤ val ≤ 100
  • 1 ≤ n ≤ sz
  • the page’s follow-up: do it in one pass

The signature is function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null. Try it on LeetCode first.

Hint

Put two pointers a fixed number of nodes apart and move them together. Where is the back one when the front one falls off the end?

Interviewer: Remove the n-th node from the end of this list.

Candidate: Is n always valid?

Interviewer: Yes, from 1 to the length.

Candidate: Can the list be empty?

Interviewer: No, it has at least one node.

Candidate: Then removing the only node returns null. Must it be one pass?

Interviewer: Start with whatever works.

Candidate: Here’s my example, a playlist of six songs where I drop the 3rd from the end, and three edge cases.

list                      n  expected
[10, 20, 30, 40, 50, 60]  3  [10, 20, 30, 50, 60]
[1, 2, 3]                 3  [2, 3]       removes the head
[1, 2, 3]                 1  [1, 2]       removes the tail
[5]                       1  []           removes the only node

Candidate: The naive solution counts the nodes, then walks to the node before the target. The target is at index sz − n from the front. To remove the head, I need a node before the head, so I start from a dummy node, as in 21.

// Count the nodes, then walk to the node just before the one to remove. A dummy node before the head
// means removing the head needs no special case.
// Time O(sz): two passes. Memory O(1).
export function removeNthFromEndTwoPass(head: ListNode | null, n: number): ListNode | null {
  let length = 0;
  for (let node = head; node !== null; node = node.next) length++;
  const dummy = new ListNode(0, head);
  let before = dummy;
  for (let i = 0; i < length - n; i++) before = before.next!;
  before.next = before.next!.next;
  return dummy.next;
}

Candidate: That’s O(sz) time, two passes, and O(1) memory. At 30 nodes it fits easily.

Interviewer: Can you do it in one pass?

Candidate: The first pass only counts, so I know how far the end is. A gap between two pointers can measure that distance instead.

Candidate: I start front and back on the dummy, and move front n + 1 nodes ahead. Then I move both until front is null. Now back is n + 1 nodes before the end, which is the node right before the target.

// Two pointers n + 1 nodes apart: when the front one falls off the end, the back one is just before the target.
// Time O(sz): one pass. Memory O(1).
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
  const dummy = new ListNode(0, head);
  let front: ListNode | null = dummy;
  let back = dummy;
  for (let i = 0; i <= n; i++) front = front!.next;
  while (front !== null) {
    front = front.next;
    back = back.next!;
  }
  back.next = back.next!.next;
  return dummy.next;
}

export { removeNthFromEnd };

Interviewer: Trace your example.

Figure 4 traces the playlist with n = 3. Each row shows where the two pointers are after one move.

dummy -> [10] -> [20] -> [30] -> [40] -> [50] -> [60] -> null

move     front  back
gap 1    [10]   dummy
gap 2    [20]   dummy
gap 3    [30]   dummy
gap 4    [40]   dummy   front is n + 1 = 4 nodes ahead
both     [50]   [10]
both     [60]   [20]
both     null   [30]    back.next is [40]: unlink it

Figure 4: the gap of n + 1 nodes stays fixed, so when front falls off the end, back stops on the node before the target.

Candidate: For [1, 2, 3] with n = 3, front moves 4 nodes, from the dummy to null, and back stays on the dummy. So I unlink the head, and dummy.next is [2].

Interviewer: Final cost?

Candidate: O(sz) time, one pass. O(1) memory: the dummy and two pointers.

Interviewer: Is the one-pass version faster?

The Candidate’s answer

Candidate: Not in steps. The two-pass version moves a pointer sz + (sz − n) times, and the one-pass version moves front sz + 1 times and back sz − n times. That’s about the same. One pass is what the page asks for, and the fixed gap is the idea worth knowing.

Interviewer: What if you could keep the nodes in an array?

The Candidate’s answer

Candidate: One pass fills the array, and the node before the target is at index length - n - 1, or the target is the head when that’s -1. It’s O(sz) time, but O(sz) memory for the array.

This version isn’t in the lab.

One mistake is common here:

  • No dummy node. With both pointers starting on the head, back can’t stop before the head. [1, 2, 3] with n = 3 throws TypeError: Cannot read properties of null (reading 'next') instead of returning [2, 3]. Start both pointers on a dummy node.

Lab folder: module-06/0019-remove-nth-node-from-end-of-list/ in the course repository.

143. Reorder List

143. Reorder List is rated Medium. You get a list. Rearrange its nodes so they alternate from the two ends toward the middle: the first node, the last, the second, the second-to-last, and so on. Change the links, not the values, and return nothing.

  • 1 ≤ n ≤ 5 × 10^4 nodes
  • 1 ≤ val ≤ 1000
  • change the links; each value stays in its node

The signature is function reorderList(head: ListNode | null): void. Try it on LeetCode first.

Hint

The nodes you take from the back, in the order you take them, are the second half of the list reversed.

Interviewer: Reorder this list: first, last, second, second-to-last, and so on.

Candidate: May I swap the values instead of moving nodes?

Interviewer: No, move the nodes.

Candidate: I return nothing, and the head stays the head?

Interviewer: Yes.

Candidate: How long can it be?

Interviewer: Up to 5 × 10⁴ nodes.

Candidate: Then O(n²) is about 10⁹ steps, well over the budget. Here’s my example, guests sorted by age, and three edge cases.

list                      expected
[90, 70, 50, 30, 20, 10]  [90, 10, 70, 20, 50, 30]
[8]                       [8]          one node
[1, 2]                    [1, 2]       two nodes: already in order
[1, 2, 3]                 [1, 3, 2]    odd length: the middle ends it

Candidate: The naive solution moves the tail forward, one node at a time. From each node, it walks to the tail, unhooks it, and places it right after that node.

// For each node from the front, walk to the current tail, unhook it and place it right after that node.
// Time O(n^2): every move walks the rest of the list to find the tail. Memory O(1).
export function reorderListMoveTail(head: ListNode | null): void {
  let node = head;
  while (node !== null && node.next !== null && node.next.next !== null) {
    let beforeTail = node;
    while (beforeTail.next!.next !== null) beforeTail = beforeTail.next!;
    const tail = beforeTail.next!;
    beforeTail.next = null;
    tail.next = node.next;
    node.next = tail;
    node = tail.next;
  }
}

Candidate: There are about n/2 moves, and each one walks the rest of the list. That’s about n²/4 steps, 6.25 × 10⁸ at the limit, six times the budget. Memory is O(1).

In one call in atlimit.ts, reorderListMoveTail took 622.1 ms on 5 × 10⁴ nodes. LeetCode doesn’t publish its time limits, so we can’t say whether its judge accepts that. The two answers below took 2.4 ms and 2.7 ms on the same input.

Interviewer: What does it repeat?

Candidate: Every move walks from the front to find the tail again. If I could step backward, each next tail would be one link away. An array of the nodes gives me that.

// Put the nodes in an array, then link them from both ends towards the middle.
// Time O(n): two passes. Memory O(n): the array holds every node.
export function reorderListByArray(head: ListNode | null): void {
  const nodes: ListNode[] = [];
  for (let node = head; node !== null; node = node.next) nodes.push(node);
  let left = 0;
  let right = nodes.length - 1;
  while (left < right) {
    nodes[left].next = nodes[right];
    left++;
    if (left === right) break;
    nodes[right].next = nodes[left];
    right--;
  }
  if (nodes.length > 0) nodes[left].next = null; // the middle node is the new tail
}

Candidate: That’s O(n) time and O(n) memory.

Interviewer: Can you do it in O(1) memory?

Candidate: The nodes I take from the back are the second half of the list, read backward. So I reverse the second half once, and then every next tail is at the front of a list.

Candidate: That’s three steps I already know. I find the middle with slow and fast pointers, as in 141, and cut the list there. I reverse the second half, as in 206. Then I take one node from each half in turn, like 21’s merge, but alternating instead of comparing.

// Find the middle with slow and fast pointers, cut the list there, reverse the second half,
// then take one node from each half in turn.
// Time O(n): three passes of at most n steps. Memory O(1): only pointers are relinked.
function reorderList(head: ListNode | null): void {
  if (head === null) return;
  let slow = head;
  let fast = head;
  while (fast.next !== null && fast.next.next !== null) {
    slow = slow.next!;
    fast = fast.next.next;
  }
  // slow is the end of the first half (the first half gets the extra node when n is odd)
  let second = slow.next;
  slow.next = null;
  let prev: ListNode | null = null;
  while (second !== null) {
    const next = second.next;
    second.next = prev;
    prev = second;
    second = next;
  }
  let first: ListNode | null = head;
  second = prev;
  while (second !== null) {
    const firstNext: ListNode | null = first!.next;
    const secondNext: ListNode | null = second.next;
    first!.next = second;
    second.next = firstNext;
    first = firstNext;
    second = secondNext;
  }
}

export { reorderList };

Candidate: The first loop stops while fast.next.next is null, so slow ends on the last node of the first half. With an odd length, the first half gets the extra node.

Pause and predict. On [1, 2, 3], which node does slow stop on, and what are the two halves?

Candidate: fast starts on 1, and fast.next.next is 3, so both pointers move once: slow to 2, fast to 3. Now fast.next is null, and the loop stops. The halves are [1, 2] and [3], and the weave gives [1, 3, 2].

Interviewer: Trace your example.

Figure 5 shows the three steps on the guest list.

1. middle   [90] -> [70] -> [50] -> [30] -> [20] -> [10]
                             ^               ^
                            slow            fast   fast.next.next is null
2. cut      first   [90] -> [70] -> [50]
            second  [30] -> [20] -> [10]
3. reverse  second  [10] -> [20] -> [30]
4. weave    [90] -> [10] -> [70] -> [20] -> [50] -> [30]

Figure 5: after the second half is reversed, the next node to take from the back is always at the front of a list, so the weave needs no search.

Candidate: The weave takes 90, then 10 from the second half, then 70, then 20, then 50, then 30. When the second half runs out, the first half’s last node, 50, already points to 30, and 30 points to null.

Interviewer: Final cost?

Candidate: O(n) time: three passes of at most n steps. O(1) memory: a few pointers.

Interviewer: How would you check whether a list reads the same both ways?

The Candidate’s answer

Candidate: The same first two steps: find the middle and reverse the second half. Then I walk both halves together and compare values. It’s O(n) time and O(1) memory.

Candidate: If the caller still needs the list, I reverse the second half back and reconnect it before I return.

That’s LeetCode’s 234. Palindrome Linked List, which this course doesn’t cover. This version isn’t in the lab.

Interviewer: Array or in place: which would you write in an interview?

The Candidate’s answer

Candidate: The array version is shorter and easier to get right, and it’s O(n) time too. I’d write it first if time is short, and say it costs O(n) memory. If the interviewer wants O(1) memory, the three steps are each code I can write and test on its own.

One mistake is common here:

  • Not cutting the first half from the second. Without slow.next = null, the first half’s last node still points into the second half, and the weave closes a loop. The first 10 values of [1, 2, 3, 4] come out as [1, 4, 2, 3, 3, 3, 3, 3, 3, 3] instead of [1, 4, 2, 3]. The list never ends. Cut before you reverse.

Lab folder: module-06/0143-reorder-list/ in the course repository.

146. LRU Cache

146. LRU Cache is rated Medium. An LRU cache (least recently used) is a cache of fixed size. When it is full and a new key arrives, it drops the key that was read or written longest ago. To evict a key is to drop it to make room. Build one: get returns a key’s value, or -1 when it’s absent, and put adds or updates a key.

  • 1 ≤ capacity ≤ 3000
  • 0 ≤ key ≤ 10^4, 0 ≤ value ≤ 10^5
  • at most 2 × 10^5 calls to get and put
  • get and put must each run in O(1) average time

LeetCode’s TypeScript template is a class LRUCache with constructor(capacity: number), get(key: number): number and put(key: number, value: number): void. Try it on LeetCode first.

Hint

A Map finds a key in O(1). What structure lets you move one entry to the front, and drop the last one, in O(1)?

Interviewer: Build an LRU cache with O(1) get and put.

Candidate: Does put on a key that’s already there count as a use?

Interviewer: Yes. It updates the value and makes the key the most recent.

Candidate: Can a value be -1?

Interviewer: No, values are 0 or more.

Candidate: Then -1 is safe as “absent”. Can the capacity be 0?

Interviewer: No, at least 1.

Candidate: With 2 × 10⁵ calls and a capacity up to 3,000, O(capacity) per call would be 6 × 10⁸ steps. Here’s my example, a cache of 3 user profiles, and three edge cases.

capacity 3
put 10, put 20, put 30, get 10   get returns 10's value
put 40                           evicts 20: 10 was read after it
get 20                           -1
get 10, get 30, get 40           all present

capacity 1: put 1, put 2, get 1  -1      every new key evicts the other
capacity 2: put 1, put 2,        get 1 returns 10, get 2 returns -1:
  put 1 again (10), put 3                the update made 1 recent
get on an empty cache            -1

Candidate: The naive solution keeps the values in a Map and the keys in an array, from least to most recently used. Each use removes the key from the array and pushes it at the end. To evict, I shift the first key off.

// A Map for the values and an array of keys from least to most recently used.
// Time O(capacity) per call: indexOf and splice scan and shift the array. Memory O(capacity).
export class LRUCacheArray {
  capacity: number;
  values = new Map<number, number>();
  order: number[] = []; // order[0] is the least recently used key

  constructor(capacity: number) {
    this.capacity = capacity;
  }

  private touch(key: number): void {
    const i = this.order.indexOf(key);
    if (i !== -1) this.order.splice(i, 1);
    this.order.push(key);
  }

  get(key: number): number {
    const value = this.values.get(key);
    if (value === undefined) return -1;
    this.touch(key);
    return value;
  }

  put(key: number, value: number): void {
    this.values.set(key, value);
    this.touch(key);
    if (this.order.length > this.capacity) this.values.delete(this.order.shift()!);
  }
}

Candidate: indexOf, splice and shift are each O(capacity), so every call is O(capacity). That’s 6 × 10⁸ steps on paper at the limit. Memory is O(capacity).

In atlimit.ts, 2 × 10⁵ puts that all evicted took 133.8 ms, because indexOf and splice run in native code. So the clock likely allows it. But the page asks for O(1) per call, and this answer breaks that rule.

Interviewer: What does it repeat?

Candidate: Every use searches the array for the key’s position. If the Map gave me the key’s place in the order, I wouldn’t search. But even then, removing from the middle of an array shifts everything after it.

Candidate: A doubly linked list removes a node in O(1), because the node knows both its neighbors. So the Map stores each key’s node, and the list keeps the nodes from most to least recently used.

A doubly linked list is a list whose nodes also point to the previous node. Holding a node, you can unlink it in O(1) without walking from the head.

Candidate: I put a dummy node at each end, head and tail. Then every real node has a node on both sides, and no insert or unlink needs a null check.

Figure 6 shows the cache from the Candidate’s example after put 40. A <-> link points both ways.

Map   10 -> its node    30 -> its node    40 -> its node

head <-> [40] <-> [10] <-> [30] <-> tail
          ^                 ^
     most recent       least recent: evicted next

Figure 6: the Map finds a key’s node in O(1), and the node’s two links let it leave the list in O(1).

class CacheNode {
  key: number;
  value: number;
  prev: CacheNode | null = null;
  next: CacheNode | null = null;
  constructor(key: number, value: number) {
    this.key = key;
    this.value = value;
  }
}

// A Map from key to node, and a doubly linked list of nodes from most to least recently used.
// Two dummy nodes (head and tail) mean no insert or unlink needs a null check.
// Time O(1) per call: one Map operation and a few pointer writes. Memory O(capacity): one node and one Map entry per key.
class LRUCache {
  capacity: number;
  nodes = new Map<number, CacheNode>();
  head = new CacheNode(0, 0); // head.next is the most recently used
  tail = new CacheNode(0, 0); // tail.prev is the least recently used

  constructor(capacity: number) {
    this.capacity = capacity;
    this.head.next = this.tail;
    this.tail.prev = this.head;
  }

  private unlink(node: CacheNode): void {
    node.prev!.next = node.next;
    node.next!.prev = node.prev;
  }

  private pushFront(node: CacheNode): void {
    node.prev = this.head;
    node.next = this.head.next;
    this.head.next!.prev = node;
    this.head.next = node;
  }

  get(key: number): number {
    const node = this.nodes.get(key);
    if (node === undefined) return -1;
    this.unlink(node);
    this.pushFront(node);
    return node.value;
  }

  put(key: number, value: number): void {
    const existing = this.nodes.get(key);
    if (existing !== undefined) {
      existing.value = value;
      this.unlink(existing);
      this.pushFront(existing);
      return;
    }
    const node = new CacheNode(key, value);
    this.nodes.set(key, node);
    this.pushFront(node);
    if (this.nodes.size > this.capacity) {
      const oldest = this.tail.prev!;
      this.unlink(oldest);
      this.nodes.delete(oldest.key);
    }
  }
}

export { LRUCache };

Candidate: Each node stores its key, so on eviction I know which Map entry to delete. To paste this into LeetCode, I paste CacheNode with it.

Interviewer: Trace your example.

Figure 7 runs the Candidate’s calls. Each key k holds the value 10 × k in the lab test, so 10 holds 100.

call         returns  list, most recent first
put 10 100            10
put 20 200            20 10
put 30 300            30 20 10
get 10       100      10 30 20
put 40 400            40 10 30     full: 20 at the tail is evicted
get 20       -1       40 10 30
get 10       100      10 40 30
get 30       300      30 10 40
get 40       400      40 30 10

Figure 7: every get and put moves its key to the front, so the tail is always the key used longest ago.

Interviewer: Final cost?

Candidate: O(1) average per call: one Map operation and a few link writes. The average comes from the Map. Memory is O(capacity): one node and one Map entry per key.

In the same atlimit.ts run, LRUCache took 16.3 ms for the 2 × 10⁵ evicting puts, against 133.8 ms for the array.

Interviewer: A JavaScript Map keeps its keys in insertion order. Why not use a Map alone?

The Candidate’s answer

Candidate: It works, and it’s short. delete and then set moves a key to the end, so the first key is the least recently used one.

// A Map alone: it keeps keys in insertion order, so delete + set moves a key to the end, and the first key is the oldest.
// Time O(1) for get and for put without eviction. An eviction reads keys().next(), which in V8 steps over every
// deleted entry still at the front of the table: up to O(capacity) (DSA Module 4 notes, measured). Memory O(capacity).
export class LRUCacheMap {
  capacity: number;
  values = new Map<number, number>();

  constructor(capacity: number) {
    this.capacity = capacity;
  }

  get(key: number): number {
    const value = this.values.get(key);
    if (value === undefined) return -1;
    this.values.delete(key);
    this.values.set(key, value);
    return value;
  }

  put(key: number, value: number): void {
    this.values.delete(key);
    this.values.set(key, value);
    if (this.values.size > this.capacity) this.values.delete(this.values.keys().next().value!);
  }
}

Candidate: But eviction isn’t O(1) in V8. A deleted entry stays in the Map‘s table as a hole until the table is rebuilt. A cache that keeps evicting its oldest key piles those holes up at the front, and keys().next() steps over every one of them.

In atlimit.ts, LRUCacheMap took 353.6 ms for the 2 × 10⁵ evicting puts, against 16.3 ms for the list. With random keys from 0 to 10⁴, half gets and half puts, it took 94.2 ms against 12.3 ms. It still passes on time, but its O(1) claim doesn’t hold in V8. “Underneath”, near the end of this page, explains the holes.

Candidate: So I’d say it out loud: a Map alone is fine for a cache that rarely evicts, and the list is the guaranteed O(1).

Interviewer: What if entries should also expire after a time?

The Candidate’s answer

Candidate: I’d store the time each node was written. get checks it, and treats an expired node as absent: it unlinks the node and deletes it from the Map. The list order stays the same, so every call is still O(1).

This version isn’t in the lab.

Two mistakes are common here. mistakes.ts makes both in the Map-only version from the first follow-up.

  • get doesn’t move the key to most recent. Then reads don’t protect a key from eviction. With capacity 2, put 1, put 2, get 1, put 3, get 1 returns -1 instead of 1. Every get that finds the key must move it.
  • put on an existing key only updates the value. A Map‘s set on an existing key keeps its old place. With capacity 2, put 1, put 2, put 1 again with 10, put 3, get 1 returns -1 instead of 10. Move the key on every put, too.

Lab folder: module-06/0146-lru-cache/ in the course repository.

23. Merge k Sorted Lists

23. Merge k Sorted Lists is rated Hard. You get an array of k lists, each sorted from small to large. Combine all their nodes into one sorted list and return its head.

  • 0 ≤ k ≤ 10^4 lists
  • each list has 0 to 500 nodes, sorted ascending
  • -10^4 ≤ val ≤ 10^4
  • N, the total number of nodes, is at most 10^4

The signature is function mergeKLists(lists: Array<ListNode | null>): ListNode | null. Try it on LeetCode first.

Hint

The next node is always one of the k current heads. What structure gives you the smallest of k items faster than looking at all k?

Interviewer: Merge these k sorted lists into one.

Candidate: Can the array be empty, or hold empty lists?

Interviewer: Both. k can be 0, and any list can be null.

Candidate: How big can it get?

Interviewer: Up to 10⁴ lists, and 10⁴ nodes in all.

Candidate: Can values repeat?

Interviewer: Yes, in any order among equals.

Candidate: Here’s my example, event times logged by three servers, and two edge cases.

lists                                  expected
[3, 8, 15], [1, 9], [4, 4, 20, 21]     [1, 3, 4, 4, 8, 9, 15, 20, 21]
[], [2], []                            [2]          empty lists around one
[5], [4], [3], [2], [1]                [1, 2, 3, 4, 5]   many one-node lists

Candidate: The naive solution is 21’s merge with k heads. At each step I scan all k heads for the smallest, attach it, and move that list forward.

// Each step, scan the heads of all k lists for the smallest and attach it.
// Time O(N k) for N nodes in all: every one of the N steps reads k heads. Memory O(k): the copy of the k heads.
export function mergeKListsScanHeads(lists: Array<ListNode | null>): ListNode | null {
  const heads = [...lists]; // a copy, so the caller's array is not changed
  const dummy = new ListNode();
  let tail = dummy;
  while (true) {
    let smallest = -1;
    for (let i = 0; i < heads.length; i++) {
      if (heads[i] !== null && (smallest === -1 || heads[i]!.val < heads[smallest]!.val)) smallest = i;
    }
    if (smallest === -1) break;
    tail.next = heads[smallest];
    tail = tail.next!;
    heads[smallest] = tail.next;
  }
  tail.next = null;
  return dummy.next;
}

Candidate: That’s O(N × k) time: N steps, each reading k heads. Memory is O(k) for the copy of the heads. At 10⁴ one-node lists, that’s 10⁸ steps, right at the budget.

In atlimit.ts, it took 260.2 ms on 10⁴ one-node lists, so it fits LeetCode’s limits.

Candidate: I could also put every node in an array and sort it, as in 21’s naive answer. That’s O(N log N) time and O(N) memory, and it took 2.7 ms on the same lists. But it ignores that each list is already sorted.

Interviewer: Say there were 10⁵ lists and 10⁶ nodes. What does the scan repeat?

Candidate: Then it’s 10¹¹ steps. After each step, only one head changed, but I compare all k heads again. I need a structure that keeps the heads partly in order, so finding the smallest doesn’t read all of them.

Candidate: That’s a min-heap of the heads. I pop the smallest head, attach it, and push that node’s next if there is one.

A min-heap is a tree stored in an array that always has its smallest item on top. Reading the top is O(1), and adding or removing an item is O(log k) for k items. Module 1 named it in a stretch answer, Module 8 works heap problems, and DSA Module 8 builds it and shows how push and pop keep it in order.

JavaScript has no heap, so the lab uses the one DSA Module 8 writes, shared/heap.ts. You only need its public part here:

// excerpt: the methods of Heap in lab/shared/heap.ts that this module uses
declare class Heap<T> {
  // before(a, b) is true when a must come out before b: (a, b) => a.val < b.val is a min-heap.
  // Builds the heap from items in O(n), in place.
  constructor(before: (a: T, b: T) => boolean, items?: T[]);
  get size(): number;
  push(item: T): void; // O(log n)
  pop(): T | undefined; // O(log n): removes and returns the top
}
// A min-heap holds the current head of each non-empty list. Pop the smallest, attach it, push its next node.
// Time O(N log k): N pops and up to N pushes on a heap of at most k nodes. Memory O(k): the heap.
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
  const heads = lists.filter((node): node is ListNode => node !== null);
  const heap = new Heap<ListNode>((a, b) => a.val < b.val, heads);
  const dummy = new ListNode();
  let tail = dummy;
  while (heap.size > 0) {
    const node = heap.pop()!;
    tail.next = node;
    tail = node;
    if (node.next !== null) heap.push(node.next);
  }
  tail.next = null;
  return dummy.next;
}

export { mergeKLists };

Candidate: I drop the empty lists before building the heap, because a null has no val to compare. The heap never holds more than one node per list, so at most k nodes.

To paste this into LeetCode, paste the Heap class from heap.ts with it, about 60 lines. LeetCode’s help page on its environments (updated 20 November 2026) also lists @datastructures-js/priority-queue 6.3.5 among the packages its JavaScript and TypeScript editors include. There a min-heap of nodes is new MinPriorityQueue<ListNode>((node) => node.val), with enqueue, dequeue and size(), a method rather than a getter. In an interview, ask whether you may use it. This version isn’t in the lab.

Interviewer: Trace your example.

Figure 8 traces the three servers’ lists. L0, L1 and L2 name the lists. The heap column lists the values it holds from small to large; the array inside the heap keeps them in another order.

L0  [3] -> [8] -> [15]
L1  [1] -> [9]
L2  [4] -> [4] -> [20] -> [21]

step   pop      push  heap holds  result so far
start                 1 3 4
1      1 (L1)   9     3 4 9       1
2      3 (L0)   8     4 8 9       1 3
3      4 (L2)   4     4 8 9       1 3 4
4      4 (L2)   20    8 9 20      1 3 4 4
5      8 (L0)   15    9 15 20     1 3 4 4 8
6      9 (L1)   -     15 20       1 3 4 4 8 9
7      15 (L0)  -     20          1 3 4 4 8 9 15
8      20 (L2)  21    21          1 3 4 4 8 9 15 20
9      21 (L2)  -     empty       1 3 4 4 8 9 15 20 21

Figure 8: the heap holds one head per list that isn’t used up, so the smallest node left is always on top.

Candidate: For [], [2], [], the heap starts with only [2]. One pop attaches it, there’s no next to push, and the result is [2].

Interviewer: Final cost?

Candidate: O(N log k) time: N pops and at most N pushes, each O(log k) on a heap of at most k nodes. Building the heap is O(k). O(k) memory for the heap.

In atlimit.ts, mergeKLists took 2.4 ms on the 10⁴ one-node lists, against 260.2 ms for the scan.

A merge of k sorted sequences into one is a k-way merge. Sedgewick and Wayne’s Algorithms, section 2.4 does it with a heap in the same way.

Interviewer: Can you do it without a heap?

The Candidate’s answer

Candidate: Yes, with 21’s merge. I merge the lists in pairs: 0 with 1, 2 with 3, and so on. Then I merge the results in pairs again, until one list is left, as a bottom-up merge sort does.

// Merge two sorted lists by relinking (Problem 21).
function mergeTwo(a: ListNode | null, b: ListNode | null): ListNode | null {
  const dummy = new ListNode();
  let tail = dummy;
  while (a !== null && b !== null) {
    if (a.val <= b.val) {
      tail.next = a;
      a = a.next;
    } else {
      tail.next = b;
      b = b.next;
    }
    tail = tail.next;
  }
  tail.next = a !== null ? a : b;
  return dummy.next;
}

// Merge the lists in pairs, round after round, as merge sort does: k lists, then k/2, k/4, ... down to one.
// Time O(N log k): each round touches every node once, and there are about log2 k rounds. Memory O(k): the array of lists.
export function mergeKListsInPairs(lists: Array<ListNode | null>): ListNode | null {
  if (lists.length === 0) return null;
  let round = lists;
  while (round.length > 1) {
    const next: Array<ListNode | null> = [];
    for (let i = 0; i < round.length; i += 2) next.push(mergeTwo(round[i], i + 1 < round.length ? round[i + 1] : null));
    round = next;
  }
  return round[0];
}

Candidate: Each round touches every node once and halves the number of lists. So it’s O(N log k) time, the same as the heap, and O(k) memory for the arrays of lists. On my example, round 1 merges L0 with L1 and L2 with nothing, and round 2 merges the two results.

Pause and predict. How many rounds does mergeKListsInPairs need for 10⁴ lists?

Candidate: 10⁴, then 5,000, 2,500, 1,250, 625, 313, 157, 79, 40, 20, 10, 5, 3, 2 and 1. That’s 14 rounds, which is log₂ 10⁴ rounded up.

In atlimit.ts it took 1.8 ms on the 10⁴ one-node lists. It needs no heap class, so it’s the easier answer to paste. The heap version also works when lists arrive over time, because it only needs the current head of each.

Interviewer: Why not merge list 1 into the result, then list 2, and so on?

The Candidate’s answer

Candidate: Each merge walks the whole result so far again. The first list’s nodes are walked k times, so it’s O(N × k), like the scan. Merging in pairs keeps every merge between lists of about the same size.

Interviewer: What if the lists are files too large for memory?

The Candidate’s answer

Candidate: The same k-way merge works on streams. I keep a small buffer per file and the heap of the k current heads, and write each popped value to the output. Memory stays O(k) plus the buffers.

This version isn’t in the lab.

One mistake is common here:

  • Putting empty lists into the heap. The heap compares a.val, and an empty list is null. [[], [1]] throws TypeError: Cannot read properties of null (reading 'val') instead of returning [1]. Filter out the null lists first.

Lab folder: module-06/0023-merge-k-sorted-lists/ in the course repository.

Measured: Linked List Cycle, a set against two pointers

Linked List Cycle is the problem this module measures, with bench.ts from DSA Module 1. Every list has a loop: its tail links back to a random node. The sizes, 10⁵ to 4 × 10⁶ nodes, are far past LeetCode’s 10⁴, because the question is how each answer grows.

// measure.ts: Module 6's measurement. 141. Linked List Cycle, a set of every node seen against Floyd's two pointers.
// Run from the repository root: node --expose-gc module-06/measure.ts (without --expose-gc the memory part is skipped)
import { bench } from "../shared/bench.ts";
import { ListNode, fromArray } from "../shared/list-node.ts";
import { hasCycleSet, hasCycle } from "./0141-linked-list-cycle/solution.ts";

let sink = 0;

// n nodes with random values; the tail links back to a random node, so every list has a cycle.
function listWithCycle(n: number): ListNode | null {
  const head = fromArray(Array.from({ length: n }, () => Math.floor(Math.random() * 200_001) - 100_000));
  const pos = Math.floor(Math.random() * n);
  let tail = head!;
  let target = head!;
  for (let i = 0; tail.next !== null; i++) {
    if (i < pos) target = target.next!;
    tail = tail.next;
  }
  tail.next = target;
  return head;
}

const sizes = [100_000, 1_000_000, 4_000_000];
bench("set of every node seen", sizes, listWithCycle, (head) => (sink += hasCycleSet(head) ? 1 : 0));
bench("Floyd's two pointers", sizes, listWithCycle, (head) => (sink += hasCycle(head) ? 1 : 0));

// Memory: heap growth while a Set holds every node of a 10^6-node list (what hasCycleSet builds), after gc.
const gc = (globalThis as { gc?: () => void }).gc;
if (gc) {
  const n = 1_000_000;
  const head = listWithCycle(n);
  gc();
  const before = process.memoryUsage().heapUsed;
  const seen = new Set<ListNode>();
  for (let node = head; !seen.has(node!); node = node!.next) seen.add(node!);
  gc();
  const after = process.memoryUsage().heapUsed;
  sink += seen.size;
  console.log(`\nset of ${n.toLocaleString("en-US")} nodes: ${((after - before) / n).toFixed(1)} bytes per node; Floyd's pointers: 2 variables`);
}

console.log(`\nsink ${sink}`);

bench runs each size once to warm up, then five times on fresh lists, and prints the median and how many times slower each size is than the one before. Building the list isn’t timed. --expose-gc lets the script run the garbage collector, so the memory line measures only what the set adds.

Pause and predict. Both answers are O(n) time. Which one do you expect to be faster per node, given that Floyd’s pointers can go around the loop more than once?

Here is what node --expose-gc module-06/measure.ts printed:


set of every node seen
             n   median ms   x prev
       100,000        2.77         
     1,000,000       27.25      9.8
     4,000,000      136.46      5.0

Floyd's two pointers
             n   median ms   x prev
       100,000        0.17         
     1,000,000        2.58     15.5
     4,000,000        9.22      3.6

set of 1,000,000 nodes: 21.0 bytes per node; Floyd's pointers: 2 variables

sink 1000036

These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.

Both grew about linearly. From 10⁶ to 4 × 10⁶ nodes, four times more, the set took 5.0 times longer and the pointers 3.6 times. The set’s step is a little more than 4, and we didn’t look into why. The pointers’ 15.5 starts from 0.17 ms, a time small enough to move between runs: the same file run earlier, at a higher machine load, gave 12.6.

Floyd’s pointers were 10 to 16 times faster at every size, though they walk the loop more than once. Each step of the set hashes a node and inserts it, while each step of the pointers follows three links. The memory line is the follow-up’s point: the set needed 21.0 bytes per node, 21 MB at 10⁶ nodes, and the pointers need two variables. sink counts the results, so V8 can’t skip the calls.

Underneath: what a node and a set cost in V8

JavaScript has no built-in linked list, so ListNode is a plain class, and each node is an ordinary object. DSA Module 4 measures a { val, next } node at 40 bytes when Node.js is built without pointer compression. That’s three internal pointers and the two fields, at 8 bytes each. Node.js 24.22.1 on this Mac is built the same way. That’s five times the 8 bytes an array of small integers spends per item, and walking a list follows a pointer per node instead of reading memory in order. DSA Module 4 measures that cost too.

The Set in hasCycleSet added 21.0 bytes per node. V8 13.6, the engine in Node.js 24.22.1, stores a Set as an ordered hash table. Each entry takes 2 slots, the key and a link to the next entry in its bucket, and there is one bucket per 2 entries. The capacity rounds up to a power of two, so 10⁶ nodes get 2²⁰ entries: 2²⁰ × 2.5 slots × 8 bytes / 10⁶ = 20.97 bytes, the 21.0 measured.

That table is also why 146’s Map-only cache slows down. The specification guarantees that a Map visits keys in insertion order (ECMAScript 2025, Map.prototype.forEach). V8 keeps that order by appending each new entry, and delete leaves a hole until the table is rebuilt. A cache that always evicts its oldest key collects those holes at the front, and every keys() iterator steps over them. DSA Module 4 reads that code in V8 12.4 and 14.6 and measures it. Node.js 24 ships V8 13.6, between the two, and we didn’t reread its source, but atlimit.ts shows the same slowdown.

The recursive answers in 206 and 21 use the call stack, which V8 caps at 984 KB on this arm64 build (node --v8-options lists --stack-size). reverseListRecursive handled 8,885 nodes in one run, and the number moves with how far the JIT compiler has optimized the function. DSA Module 6 measures how many frames fit. 23’s heap is DSA Module 8‘s binary heap over a plain array.

Cheat sheet

Figure 9 maps each problem in this module to the sign that pointed to its solution.

sign in the problem                 problem  the pointers           cost
turn every link around              206      prev, node, saved next O(n)
merge two sorted lists              21       dummy node and a tail  O(n + m)
does it loop, in O(1) memory        141      slow and fast          O(n)
n-th node from the end, one pass    19       two, n + 1 apart       O(sz)
first, last, second, ... in place   143      middle, reverse, weave O(n)
O(1) get and put, drop the oldest   146      Map + doubly linked    O(1) each
merge k sorted lists                23       min-heap of k heads    O(N log k)

Figure 9: on a list, the fast answer keeps a pointer on each node it needs next, so it never walks to find one.

  • Pattern: relink in place with a few pointers; save next before you overwrite it; start a result with a dummy node.
  • Two pointers on a list: different speeds find a cycle or the middle; a fixed gap finds the n-th node from the end.
  • Signs: a ListNode input; “in one pass” or “O(1) memory”; a position from the end; find a key and move it to the front in O(1).
  • Final costs: 206, 21, 141, 19 and 143 in O(n) time and O(1) memory; 146 in O(1) per call and O(capacity) memory; 23 in O(N log k) time and O(k) memory.
  • Next: Module 7 works binary trees, where each node has two pointers and recursion is the natural answer.

Sources