Flatten a Multilevel Doubly Linked List
Difficulty: Medium · Pattern: Linked List · LeetCode #430
A doubly linked list where nodes may also have a child pointer to another doubly linked list (which may have children too). Flatten it into a single level: a node's child list comes right after the node and before its next. All child pointers must be null afterwards, and prev pointers must be correct.
The tests describe the structure as nested arrays [[val, childList|null], …]; the expected output is the flattened values.
Example
1 - 2 - 3 - 4 - 5 - 6
|
7 - 8 - 9 - 10
|
11 - 12
→ 1 2 3 7 8 11 12 9 10 4 5 6Hints
- This is a pre-order DFS: node, then child list, then next.
- Iteratively: when you see a child, find the child list's tail, splice the list between the node and node.next, then continue.
Approach
Walk with cur. When cur.child exists: find the tail of the child list, then splice: tail.next = cur.next (and fix cur.next.prev), cur.next = child, child.prev = cur, cur.child = null. Continue from cur.next. Nested children are handled when the walk reaches them. O(n) total (each node is visited a bounded number of times), O(1) extra space.
Complexity
Time: O(n). Space: O(1).
Python solution
def flatten(head):
cur = head
while cur:
if cur.child:
child, tail = cur.child, cur.child
while tail.next:
tail = tail.next
tail.next = cur.next
if cur.next:
cur.next.prev = tail
cur.next, child.prev, cur.child = child, cur, None
cur = cur.next
return headJavaScript solution
function flatten(head) {
for (let cur = head; cur; cur = cur.next) {
if (cur.child) {
const child = cur.child; let tail = child;
while (tail.next) tail = tail.next;
tail.next = cur.next; if (cur.next) cur.next.prev = tail;
cur.next = child; child.prev = cur; cur.child = null;
}
}
return head;
}