CodeArchon

easyLinked ListAmazonMicrosoftApple

Merge Sorted Chains

Two already-sorted sensor logs stream in. Weave them into one sorted log in place.

Given the heads of two sorted singly linked lists, splice them into one sorted linked list.

Choose approach

1
a
2
4
1
b
3
4
nil
1/7
Narrationstep 1 of 7

Walk both chains in lockstep; always append the smaller head to the merged tail.

1def merge_sorted_chains(a, b):
2 dummy = ListNode(0)
3 tail = dummy
4 while a and b:
5 if a.val <= b.val:
6 tail.next, a = a, a.next
7 else:
8 tail.next, b = b, b.next
9 tail = tail.next
10 tail.next = a or b
11 return dummy.next
Variables
aLen=3
bLen=3

How to think about it

  1. No new nodes — only rewire existing `.next` pointers.
  2. A dummy head node simplifies the first splice.
  3. When one chain runs out, the other is already sorted — attach it whole.

Edge cases to catch in interview

  • Either list empty → the other.
  • Both empty → empty.
  • Equal values — pick A first for stability.

Examples

Example 1[1,1,2,3,4,4]
{"aVals":[1,2,4],"bVals":[1,3,4]}
Example 2[]
{"aVals":[],"bVals":[]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed