Flatten a Multilevel Doubly Linked List
MedPrompt
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.
Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.
Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.
Example 1:
Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:Example 2:
Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:Example 3:
Input: head = []
Output: []
Explanation: There could be empty list in the input.
Constraints:
- The number of Nodes will not exceed
1000. 1 <= Node.val <= 105
How the multilevel linked list is represented in test cases:
We use the multilevel linked list from Example 1 above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULLThe serialization of each level is as follows:
[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
[1, 2, 3, 4, 5, 6, null]
|
[null, null, 7, 8, 9, 10, null]
|
[ null, 11, 12, null]Merging the serialization of each level and removing trailing nulls we obtain:
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]Approaches
3 approaches with complexity analysis and trade-offs.
This approach uses recursion to perform a depth-first traversal of the multilevel list. A helper function is designed to flatten a given sublist and return its tail. This allows the parent level to correctly link the flattened child list into place before continuing its own traversal.
Algorithm
- Define a recursive function, let's call it
flattenRec(node), which takes a node, flattens the list starting from it, and returns the tail of the flattened list. - The main
flattenfunction will call this recursive helper on theheadand return thehead. - Inside
flattenRec(node):- Initialize a
currpointer tonodeand atailpointer, also tonode. - Iterate while
curris not null. - If
currhas achild: a. Storecurr.nextin a temporary variable,nextNode. b. Make a recursive callflattenRec(curr.child)to flatten the child sublist. This call returns the tail of the flattened child list, let's call itchildTail. c. Splice the child list in: setcurr.nexttocurr.child,curr.child.prevtocurr, andcurr.childtonull. d. Connect the end of the newly inserted child list to the rest of the original list: setchildTail.nexttonextNode, and ifnextNodeis not null, setnextNode.prevtochildTail. e. Update the overalltailof the processed list to bechildTail. f. Crucially, continue the iteration by settingcurrtonextNode. - If
currhas no child, simply updatetail = currand move to the next nodecurr = curr.next.
- Initialize a
- After the loop finishes, return the
tail.
Walkthrough
The core idea is to solve the problem by breaking it down into smaller, identical subproblems, which is a natural fit for recursion. We can define a recursive function that takes the head of a list (or sublist) and flattens it. A key part of the design is that this function must return the tail of the flattened list it produces. This is necessary so that the caller, which is processing a higher-level list, knows where to attach the rest of its own list.
The process for a given node curr is as follows: if curr has a child, we first recursively flatten that child's list. Once that's done and we have the tail of the flattened child list, we can 'splice' this list into the main list. This involves re-wiring the next and prev pointers of curr, the head of the child list, the tail of the child list, and curr's original next node. After splicing, we set curr.child to null as required and continue our traversal from where the spliced list ends.
/*// Definition for a Node.class Node { public int val; public Node prev; public Node next; public Node child;};*/class Solution { public Node flatten(Node head) { if (head == null) { return null; } flattenRec(head); return head; } // Flattens the list starting at 'node' and returns the tail of the flattened list. private Node flattenRec(Node node) { Node curr = node; Node tail = node; // Keep track of the last node visited while (curr != null) { Node nextNode = curr.next; if (curr.child != null) { // Flatten the child list and get its tail Node childTail = flattenRec(curr.child); // Splice the child list in curr.next = curr.child; curr.child.prev = curr; curr.child = null; // Connect the child tail to the original next node childTail.next = nextNode; if (nextNode != null) { nextNode.prev = childTail; } // The new tail of the list processed so far is the child's tail tail = childTail; // The next node to process is what was originally after the child tail curr = nextNode; } else { // No child, just move to the next node tail = curr; curr = nextNode; } } return tail; }}Complexity
Time
O(N), where N is the total number of nodes in the list. Each node is visited a constant number of times during the traversal and pointer manipulation.
Space
O(D), where D is the maximum depth of the child lists. In the worst-case scenario (a linked list where each node's `next` is null and `child` is not), the recursion depth can be N, leading to O(N) space complexity for the call stack.
Trade-offs
Pros
The solution is elegant and closely mirrors the recursive definition of the data structure.
The code can be relatively clean and easy to understand for those familiar with recursion.
Cons
Can lead to a
StackOverflowErrorif the list is very deep (i.e., has many nested child levels).Recursion can introduce performance overhead compared to an iterative solution.
Solutions
Solution
/* // Definition for a Node. class Node { public int val; public Node prev; public Node next; public Node child; }; */ class Solution { public Node flatten ( Node head ) { if ( head == null ) { return null ; } Node dummy = new Node (); dummy . next = head ; preorder ( dummy , head ); dummy . next . prev = null ; return dummy . next ; } private Node preorder ( Node pre , Node cur ) { if ( cur == null ) { return pre ; } cur . prev = pre ; pre . next = cur ; Node t = cur . next ; Node tail = preorder ( cur , cur . child ); cur . child = null ; return preorder ( tail , t ); } }Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.