Skip to content
mlmentorship

Attach the smaller sorted frontier and advance only its source

Prove two-frontier sufficiency, preserve node identity while rewiring, then copy the output or change both source and comparison order.

Published · 16 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Attach the smaller sorted frontier and advance only its source

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Two heads of nondecreasing linked lists with comparable values; either head may be None. Output. Return the head of a nondecreasing chain containing every node from both lists exactly once. Rules. The input chains must be acyclic and node-disjoint, with permission to rewrite their links. Reuse the original nodes rather than creating replacement output nodes. Retain equal-valued occurrences. Two empty inputs return None; one empty input leaves the other chain as the result. Example. A: 1 -> 4 -> 7 and B: 2 -> 3 -> 8 produce 1 -> 2 -> 3 -> 4 -> 7 -> 8. The nodes valued 1 and 2 are still the original A and B nodes, not copies.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Compare the two frontier nodes, link the smaller after tail, and advance only its source cursor.

Problem trace

Attach the remaining suffix directly once the other list is exhausted

Input and goalMerge two sorted linked lists into one sorted list.
Initialize two sorted chainstail=dummy, first=A1, second=B2, and dummy.next=null.
Linked-list topologyNodes, next pointers, and moving algorithm pointers.ABouttaildummyfirstA1A4A7secondB2B3B8
inputA:1->4->7; B:2->3->8fixedPrefixempty
edges
[A1 -> A4, A4 -> A7, B2 -> B3, B3 -> B8]
input
A:1->4->7; B:2->3->8
fixed prefix
empty

Recognize it
Two sorted node streams must be merged by relinking existing nodes.
Keep true
The path from dummy through tail is the consumed sorted prefix; first and second begin untouched suffixes. The old link after tail may remain until the next attachment overwrites it.
Reuse it
Emit the smaller frontier and advance only its source; append the remaining sorted suffix in constant time.
tail=dummy, first=A1, second=B2, and dummy.next=null. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does attaching the remaining B8 finish the output without moving tail away from A7?
Full interview answer 16 min read

Combine two sorted linked lists into one sorted chain while reusing all their original nodes.

Problem

Input. Two heads of nondecreasing linked lists with comparable values; either head may be None.

Output. Return the head of a nondecreasing chain containing every node from both lists exactly once.

Rules. The input chains must be acyclic and node-disjoint, with permission to rewrite their links. Reuse the original nodes rather than creating replacement output nodes. Retain equal-valued occurrences. Two empty inputs return None; one empty input leaves the other chain as the result.

Example. A: 1 -> 4 -> 7 and B: 2 -> 3 -> 8 produce 1 -> 2 -> 3 -> 4 -> 7 -> 8. The nodes valued 1 and 2 are still the original A and B nodes, not copies.

Picture

Keep two unconsumed heads, first and second, plus the last selected node, tail. A dummy node provides one uniform attachment point, including the first result.

Any later value in either sorted suffix is at least its head value. Therefore, the smaller head is globally next. On equality, choose first, preserving input order and first-source priority among equal values.

Select A1, B2, B3, A4, then A7. Only the chosen source advances at each decision. Now first is empty; attach the remaining B8 suffix with one assignment. No more comparisons are needed.

The path through tail is the selected prefix. Its old outgoing link may still reach an unselected node until the next attachment overwrites it. The picture separates the selected prefix from unconsumed sources; omitted old links are not assertions of None.

Problem trace

Suffix identity contrast: attach the surviving chain with one splice

Worked example: the untouched remainder is already sortedAfter one input is exhausted, append the other input head directly. Its internal links already represent the correctly ordered suffix.One splice attaches thealready-sorted surviving chainOne input is exhaustednullThe other input retains its existingsuffix links469nullAttach that same surviving head tothe output tailtail469null
Read it this way: After one input is exhausted, append the other input head directly. Its internal links already represent the correctly ordered suffix. Must the links four-to-six and six-to-nine be rebuilt after the other list is exhausted?
Reference drawing

Problem trace

Attach the remaining suffix directly once the other list is exhausted

Worked example: the untouched remainder is already sortedAfter one input is exhausted, append the other input head directly. Its internal links already represent the correctly ordered suffix.One splice attaches thealready-sorted surviving chainOne input is exhaustednullThe other input retains its existingsuffix links469nullAttach that same surviving head tothe output tailtail469null
Execution trace
Input and goalMerge two sorted linked lists into one sorted list.
Initialize two sorted chainstail=dummy, first=A1, second=B2, and dummy.next=null.
Linked-list topologyNodes, next pointers, and moving algorithm pointers.ABouttaildummyfirstA1A4A7secondB2B3B8
inputA:1->4->7; B:2->3->8fixedPrefixempty
edges
[A1 -> A4, A4 -> A7, B2 -> B3, B3 -> B8]
input
A:1->4->7; B:2->3->8
fixed prefix
empty

Recognize it
Two sorted node streams must be merged by relinking existing nodes.
Keep true
The path from dummy through tail is the consumed sorted prefix; first and second begin untouched suffixes. The old link after tail may remain until the next attachment overwrites it.
Reuse it
Emit the smaller frontier and advance only its source; append the remaining sorted suffix in constant time.
tail=dummy, first=A1, second=B2, and dummy.next=null. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does attaching the remaining B8 finish the output without moving tail away from A7?
Read it this way: After one input is exhausted, append the other input head directly. Its internal links already represent the correctly ordered suffix. Must the links four-to-six and six-to-nine be rebuilt after the other list is exhausted?

Code

The platform supplies ListNode; this definition makes the published blocks runnable together locally.

class ListNode:
   def __init__(self, val=0, next=None):
      self.val = val
      self.next = next
def merge_two_lists(first: ListNode | None, second: ListNode | None) -> ListNode | None:
   dummy = ListNode(0)
   tail = dummy

   while first and second:
      if first.val <= second.val:
         tail.next, first = first, first.next
      else:
         tail.next, second = second, second.next
      tail = tail.next

   tail.next = first or second
   return dummy.next

The tuple assignment evaluates the source successor before assigning either target. Later iterations can therefore overwrite output links without losing the unconsumed suffix. The result contains all original data nodes; the dummy is excluded.

Whole-function work is under constant-cost comparisons, with extra storage. Attaching the final suffix does not advance tail or the remaining source cursor.

Failure Check

Passing the same single node as both inputs makes the reference link that node to itself. Disjointness is a real precondition, not a harmless simplification.

Change to Independent Output Nodes

New task: Preserve every original next link.

Picture and change: Allocate one new node per selected value, including every value in the final suffix.

def merge_two_copy(first, second):
   dummy = tail = ListNode(0)
   while first or second:
      if first is not None and (second is None or first.val <= second.val):
         value, first = first.val, first.next
      else:
         value, second = second.val, second.next
      tail.next = ListNode(value)
      tail = tail.next
   return dummy.next

Check: The example keeps the same value order while sharing no output nodes with either input. All original links stay unchanged. Time remains ; allocation becomes nodes. Values themselves are assigned, not recursively copied.

Use when: Input ownership prohibits rewiring.

Change to Descending Inputs

New task: Merge two nonincreasing chains into one nonincreasing chain.

Picture and change: Choose the larger frontier with >=, retaining the same cursor and tail updates.

def merge_descending(first, second):
   dummy = tail = ListNode(0)
   while first and second:
      if first.val >= second.val:
         tail.next, first = first, first.next
      else:
         tail.next, second = second, second.next
      tail = tail.next
   tail.next = first or second
   return dummy.next

Check: [7,4,1] and [8,3,2] become [8,7,4,3,2,1], reusing their six nodes. Equal values still prefer the first source. Reversing only the comparator on ascending inputs does not satisfy this contract.

Use when: Both the source order and required output order change.

Transfer Check

Why does merging many sorted sources often use a heap?

Answer

The same frontier proof applies, but choosing the smallest among many heads needs more than one binary comparison. A heap orders those available heads efficiently.