Skip to problem
←

Flatten Sorted Bottom Lists

Hard 0 attempts

You're given a linked list where each node sits at the head of its own sorted sub-list: alongside a next pointer connecting it to the following node in the main list, every node also has a bottom pointer leading down through its own vertical sorted list. Merge everything into one fully sorted list that's linked purely through bottom pointers.

Function contract

root is the first node of a horizontal next chain, or null. Each test-input array is one sorted bottom chain. Nodes have data, next, and bottom properties; [] becomes null.

Output: Return the head of one non-decreasing bottom chain containing every original value, including duplicates. Clear next pointers. The runner displays data values along bottom links.

Example 1

Input
root = [[5,7,8,30],[10,20],[19,22,50],[28,35,40,45]]
Output
[5,7,8,10,19,20,22,28,30,35,40,45,50]

Example 2

Input
root = [[1,2]]
Output
[1,2]
Constraints
  • 0 <= number of bottom lists <= 50
  • Each bottom list is sorted in non-decreasing order and non-empty.
  • 1 <= node.data <= 1000
Topics

Approach: Merge the Bottom Lists

Walk the horizontal chain, saving each next pointer before merging its sorted bottom list into the accumulated result. Clear horizontal links so the output is a single bottom chain.

javascript
function flatteningALinkedList(root) {
  function merge(a, b) {
    const dummy = { bottom: null };
    let curr = dummy;
    while (a && b) {
      if (a.data <= b.data) { curr.bottom = a; a = a.bottom; }
      else { curr.bottom = b; b = b.bottom; }
      curr = curr.bottom;
    }
    curr.bottom = a || b;
    return dummy.bottom;
  }
  if (!root) return null;
  // Save each horizontal successor before merging; merged nodes use bottom only.
  let result = null, current = root;
  while (current) {
    const next = current.next;
    current.next = null;
    result = merge(result, current);
    current = next;
  }
  for (let node = result; node; node = node.bottom) node.next = null;
  return result;
}

Time Complexity: O(N × k) in the worst case, where N is the total number of nodes and k is the number of bottom lists

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript