One Van, Two Routes

Easytwo pointersAlso known as Merge Two Sorted Lists

Two couriers deliver along the same long street. Each route is a chain of stops, each pointing to the next, sorted by distance from the depot in metres.

One courier calls in sick, so one van must do both rounds in a single drive. 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

The merge takes 2 first because it is smaller than 3. It then takes 3, which is smaller than 5, then both 5s, then 9, which is smaller than 12, and finally the leftover 12.

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

The first courier had no stops, so the van 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 into an array, sort it, and build a new chain.

The sort costs O((n + m) log(n + m)), ignores that both routes were already sorted, and allocates a new chain. Merging walks each route once, O(n + m), and reuses the nodes.

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