A warehouse tracks its shelves as a linked list. Each shelf node has a next pointer to the next shelf, and is also the top of a column: a list of item nodes hanging below it through down pointers. Every column is sorted by value from top to bottom, but the shelves themselves are in no particular order. The team wants one list of every item, sorted.
Each node is a plain object { value, next, down }:
The top-row nodes (the shelves) are linked by next; the last one has next === null.
A column is a top-row node followed by its down chain, ending with down === null. Values in a column never decrease from top to bottom.
Every node below the top row has next === null.
Write flattenColumns(head), which relinks the nodes into one list sorted by value, using down pointers, and returns its first node.
Rules:
Reuse the existing nodes: do not create or copy nodes, and do not change any value. In the result, every node has next === null, and the last node has down === null.
The sort is stable: when values are equal, the node from the earlier column (closer to head) comes first, and within a column the original top-to-bottom order is kept.
flattenColumns(null) returns null.
There can be 20,000 columns and 200,000 nodes in total, and one column alone can hold 200,000 nodes. Merging the columns one by one into a growing result is O(n × k) and too slow, and a recursive merge overflows the call stack.