Given a linked list that can grow in both horizontal and vertical directions (right and down), flatten it into a sorted singly linked list provided that each horizontal and vertical list is already sorted.

The given linked list is similar to the standard linked list, except that it has one extra field down, which points to a vertical list. Assume that the vertical list doesn’t have any horizontal list attached to it.

 
For example, consider the following list:

Flatten Linked List

We should convert it into:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> NULL

 
We can divide this problem into two parts:

  1. Flattening: In this step, flatten the list either horizontally using the next pointers or vertically using the down pointers.
  2. Sorting: In this step, sort the flattened list using the merge sort algorithm.

This is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> None

The time complexity of the above solution is O(n.log(n)), where n is the total number of nodes in the linked list, and the auxiliary space required is O(n) for the merge sort algorithm.

 
The above solution first flattens the list and then sort it. We can combine both these steps into one step, i.e., sorting the list while flattening it. We can do this by calling the sortedMerge() routine of the merge sort algorithm, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> None