One Van, Two Routes

Easytwo pointersAlso known as Merge Two Sorted Lists

Two couriers deliver along the same long street. Each one's stops are stored as a chain: every stop points to the next one, and each chain is already sorted by the stop's position along the street, in metres from the depot.

One courier calls in sick, so a single van must do both rounds in one drive down the street. The dispatcher needs one chain with every stop from both routes, still sorted by distance.

Your task

Write mergeRoutes(first, second). Both arguments are sorted linked lists (smallest distance first; null / None means no stops). Return the head of one sorted list that contains every node of both.

If both routes have a stop at the same distance, keep both stops. Reuse the existing nodes by relinking them rather than creating new ones.

mergeRoutes(first: ListNode, second: ListNode) → ListNode

Examples

Example 1
Input
first = [2, 5, 9]
second = [3, 5, 12]
Output
[2, 3, 5, 5, 9, 12]
Why

Compare the first stops: 2 beats 3, so 2 goes first. Then 3 beats 5, then the two 5s (both kept), then 9 beats 12, and finally the 12 that is left over.

Example 2
Input
first = []
second = [7, 8]
Output
[7, 8]
Why

The first courier had no stops, so the van just follows the second route.

Constraints

  • 0 ≤ stops in each route ≤ 5,000
  • -100,000 ≤ distance ≤ 100,000 (negative means west of the depot)
  • Each route is sorted in non-decreasing order.
Start with brute force

Copy every distance from both chains into an array, sort it, and build a new chain from it.

The sort costs O((n + m) log(n + m)) and throws away the fact that both routes were already sorted. It also allocates a whole new chain. Merging walks each route once, O(n + m), and reuses the nodes you already have.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code