I was solving this LeetCode question - Flatten a Multilevel Doubly Linked List:
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
headof the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Letcurrbe a node with a child list. The nodes in the child list should appear aftercurrand beforecurr.nextin the flattened list.Return the
headof the flattened list. The nodes in the list must have all of their child pointers set tonull.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:
I have come up with below solution:
class Solution {
public Node flatten(Node head) {
if(head == null) {
return head;
}
Node curr = head;
Node prev = curr.prev;
Node next = curr.next;
while(curr != null) {
if(curr.child != null) {
Node child = flatten(curr.child);
// Get the last node of the child list
while(child.next != null) {
child = child.next;
}
Node tail = child;
curr.next = curr.child;
curr.child.prev = curr;
tail.next = next;
if(next != null) {
next.prev = tail;
}
curr.child = null;
}
// Move to next node
prev = next != null ? next.prev : curr;
curr = next;
next = next != null ? next.next : null;
}
return head;
}
}
Question
What would be the worst case time complexity of my solution?
Since I'm iterating through children to get the tail, I think it could get bad if all nodes had children, but I don't see how to derive the time complexity.
For example:
1 <-> 2 <-> 3 <-> 4
| | | |
5 6 7 8
| | | |
9 10 11 12
| | | |
13 14 15 16
1 <-> 2 <-> 3 <-> 4 ...
| | | |
5 6 7 8 <-> 17 <-> 19
| | | | | |
9 10 11 12 18 20 ...
| | | | . .
13 14 15 16 . .

