oneby7

Linked Lists Reversing and rewiring

310. Flatten a Linked List

Hard

You are given root, the first node of a linked list in which every node has two pointers, next and bottom. The nodes linked by next from root form the top row. Each node of the top row is also the first node of a vertical list, linked by bottom, and every vertical list is sorted in non-decreasing order. The top row itself does not have to be sorted.

Flatten the structure into one list sorted in non-decreasing order, linked through bottom, made of the given nodes, and return its head. Every node of the answer must have its next set to null.

Non-decreasing order means each value is at least the one before it, so equal values can sit next to each other. The answer keeps every node, duplicates included.

The examples write the structure as one array per vertical list: the top row from left to right, and each vertical list from its top node down. So root = [[3,9],[5]] is the top row 3 → 5, with 9 below 3. The output shows the list you return as its values along bottom.

Example 1

Input: root = [[4, 9, 15], [2, 6], [7, 8, 20, 31], [11]]

Output: [2,4,6,7,8,9,11,15,20,31]

Explanation: The top row is 4 → 2 → 7 → 11, and it is not sorted. The answer holds all ten nodes in order, and every node's next is null.

Example 2

Input: root = [[-3, -3, 0], [-3], [1, 1]]

Output: [-3,-3,-3,0,1,1]

Explanation: The three -3s come from two vertical lists, and all three are kept, side by side.

Example 3

Input: root = [[12, 40, 40, 57]]

Output: [12,40,40,57]

Explanation: The top row has one node, so its vertical list is already the answer.

Check your understanding

Work out the answer for this input before you write any code.

root = [[2, 10], [4], [1, 12]]

Constraints

  • 1 ≤ k ≤ 105, where k is root.length, the number of nodes in the top row
  • 1 ≤ total number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • Each vertical list has at least one node and is sorted in non-decreasing order.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.