LeetCode #430 Medium

Flatten a Multilevel Doubly Linked List

Flatten a Multilevel Doubly Linked List is LeetCode 430 (Medium). Each node has next and prev pointers, plus a child pointer that may lead to another doubly linked list, whose nodes can have children of their own. Flatten everything into a single level: a node's child list comes right after the node and before the node's old next. Return the head, with every child pointer set to null.

  • The list can be empty; then the answer is null.
Constraints
  • The number of nodes will not exceed 1000
  • 1 <= Node.val <= 10⁵
linked-listdfsstack
Open on LeetCode ↗
02

Intuition

The required order is: a node, then its whole child list (flattened the same way), then whatever came after the node. That is a depth-first order, and it can be built in place, because once a child list is spliced in, it is simply part of the main list.

So walk the main list from the head. When the current node has a child, find the last node of the child list, hook the child list in after the current node, and attach the old next after that last node. Then keep walking. A node inside the spliced list that has its own child is reached later by the same walk and gets the same treatment, so deeper levels need no stack and no recursion.

How to spot this pattern

A pointer that branches off a list and must be visited before the rest of the list is a depth-first order. When the structure can be rewired, splicing each branch in where it starts turns the depth-first order into a plain walk.

03

Approach

Try it first

Before reading on, draw the list 1-2-3-4-5-6 where 3 has the child 7-8-9-10 and 8 has the child 11-12. Write the flattened order, then list every pointer that changes when 7-8-9-10 is spliced in after 3.

1

Walk the main list from the head

Start cur at head and move with cur = cur.next until it is null. Every child list ends up spliced into this path before cur gets there, so one walk reaches every node on every level.

2

Find the last node of the child list

When cur.child is set, start tail at the child and follow next until tail.next is null. Only the child's own level is walked; any grandchildren still hang off their nodes and are handled when cur reaches them.

3

Splice the child list in

Save nxt = cur.next first. Then link cur.next = cur.child and cur.child.prev = cur, and set cur.child to null, since the flattened list must not keep any child pointers.

4

Attach the old next after the tail

Set tail.next = nxt, and when nxt exists, nxt.prev = tail. The rest of the original level now follows the whole child list, which is exactly the depth-first order. Then move cur on as usual.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
▶3 cur = head
▶4 while cur:
▶5 if cur.child:
▶6 tail = cur.child
▶7 while tail.next:
▶8 tail = tail.next
▶9 nxt = cur.next
▶10 cur.next = cur.child
▶11 cur.child.prev = cur
▶12 cur.child = None
▶13 tail.next = nxt
▶14 if nxt:
▶15 nxt.prev = tail
▶16 cur = cur.next
▶17 return head
1cur234567891011121 has no child → move on to 2
cur1
next2
Node 1 has no child, so nothing changes here; cur moves to 2.
12cur34567891011122 has no child → move on to 3
cur2
next3
Node 2 has no child, so nothing changes here; cur moves to 3.
123cur4567891011123 has a child → find the last node of 7's list
cur3
child7
tail7
Node 3 has a child, so the list 7… must go right after it. Before rewiring, find the last node of that child list (shown in green), because the old next of 3 will hang off it.
123cur4567891011127 has a next → the end is further on, move to 8
cur3
tail8
Node 7 is not the end of the child list, so step along to 8.
123cur4567891011128 has a next → the end is further on, move to 9
cur3
tail9
Node 8 is not the end of the child list, so step along to 9. Its own child stays where it is for now; cur will deal with it once it gets there.
123cur4567891011129 has a next → the end is further on, move to 10
cur3
tail10
Node 9 is not the end of the child list, so step along to 10.
123cur456789101112splice: 3 now leads to 7, and 10 leads on to 4
3 next7
10 next4
3 childnull
10 has no next, so it is the last node of the child list. Saved the old next (4), then linked 3 ↔ 7 in both directions and cleared 3's child. Finally 10 ↔ 4, so the rest of the old level follows the whole child list. Next, cur moves on to 7, the start of the spliced list.
1234567cur891011127 has no child → move on to 8
cur7
next8
Node 7 has no child, so nothing changes here; cur moves to 8.
12345678cur91011128 has a child → find the last node of 11's list
cur8
child11
tail11
Node 8 has a child, so the list 11… must go right after it. Before rewiring, find the last node of that child list (shown in green), because the old next of 8 will hang off it.
12345678cur910111211 has a next → the end is further on, move to 12
cur8
tail12
Node 11 is not the end of the child list, so step along to 12.
12345678cur9101112splice: 8 now leads to 11, and 12 leads on to 9
8 next11
12 next9
8 childnull
12 has no next, so it is the last node of the child list. Saved the old next (9), then linked 8 ↔ 11 in both directions and cleared 8's child. Finally 12 ↔ 9, so the rest of the old level follows the whole child list. Next, cur moves on to 11, the start of the spliced list.
1234567891011cur1211 has no child → move on to 12
cur11
next12
Node 11 has no child, so nothing changes here; cur moves to 12.
123456789101112cur12 has no child → move on to 9
cur12
next9
Node 12 has no child, so nothing changes here; cur moves to 9.
123456789cur1011129 has no child → move on to 10
cur9
next10
Node 9 has no child, so nothing changes here; cur moves to 10.
12345678910cur111210 has no child → move on to 4
cur10
next4
Node 10 has no child, so nothing changes here; cur moves to 4.
1234cur567891011124 has no child → move on to 5
cur4
next5
Node 4 has no child, so nothing changes here; cur moves to 5.
12345cur67891011125 has no child → move on to 6
cur5
next6
Node 5 has no child, so nothing changes here; cur moves to 6.
123456cur7891011126 has no child and no next → the walk is over
cur6
nextnull
Node 6 has no child to splice and is the last node, so cur becomes null and the loop stops.
123456789101112answer: 1 2 3 7 8 11 12 9 10 4 5 6
nodes12
Every child list has been spliced in where its parent was, so the list reads 1 ↔ 2 ↔ 3 ↔ 7 ↔ 8 ↔ 11 ↔ 12 ↔ 9 ↔ 10 ↔ 4 ↔ 5 ↔ 6, with every prev pointing back to the node before it.
05

Recursive depth-first search

dfs(node) flattens the level that starts at node and returns its last node. At a node with a child, it flattens the child list first, splices it in, and links the returned last node to the old next. The recursion goes one call deeper only for a child, so the stack holds one frame per level of nesting.

▶1class Solution:
▶2 def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
▶3 def dfs(node):
▶4 last = node
▶5 while node:
▶6 nxt = node.next
▶7 if node.child:
▶8 child_last = dfs(node.child)
▶9 node.next = node.child
▶10 node.child.prev = node
▶11 node.child = None
▶12 child_last.next = nxt
▶13 if nxt:
▶14 nxt.prev = child_last
▶15 last = child_last
▶16 else:
▶17 last = node
▶18 node = nxt
▶19 return last
▶20 
▶21 dfs(head)
▶22 return head
06

Common pitfalls

Overwriting next before saving it

✗ Wrong
cur.next = cur.child
cur.child.prev = cur
tail.next = cur.next
✓ Right
nxt = cur.next
cur.next = cur.child
cur.child.prev = cur
tail.next = nxt

After the first line cur.next already points at the child. On 1-2-3-4-5-6 with 3's child 7-8-9-10, node 10 gets linked back to 7, making a loop, and 4, 5 and 6 are cut off for good.

Fixing next pointers but not prev

✗ Wrong
cur.next = cur.child
tail.next = nxt
✓ Right
cur.next = cur.child
cur.child.prev = cur
tail.next = nxt
if nxt:
    nxt.prev = tail

Read forwards, the list looks right. But 7's prev is still null and 4's prev still points at 3, so walking backwards from 4 jumps straight to 3 and skips the whole child list. The result is not a valid doubly linked list.

Leaving the child pointer set

✗ Wrong
cur.next = cur.child
cur.child.prev = cur
✓ Right
cur.next = cur.child
cur.child.prev = cur
cur.child = None

Node 3 would still reach 7 through child, so the list is still multilevel. The problem asks for every child pointer to be null in the result.

07

Edge cases

The last node of a level has a child

Its old next is null, so nothing has to follow the child list. The if nxt check skips nxt.prev = tail, which would otherwise fail on a null node. 1-2-3 with 3's child 4-5 becomes 1-2-3-4-5.

Empty list

head is null, so the loop never runs and null is returned.

08

Complexity

Time
O(n)
Space
O(1)
cur visits every node once. Each child list is walked once to find its last node, and every list is spliced only once, so those walks add at most one more visit per node. Only a few pointers are stored.
09

Flatten a Multilevel Doubly Linked List FAQ

Can I use a stack instead?

Yes. When a node has a child, push its old next onto a stack and move into the child; when you reach a node with no next, pop the saved node and link it on. It is also O(n), but the stack holds one saved node per level of nesting, while the splice needs none.

How is this related to Flatten Binary Tree to Linked List?

Both produce a depth-first order in place. In Flatten Binary Tree to Linked List the left subtree goes between a node and its right subtree, just as the child list goes between a node and its next here. The tree version has no prev pointers to repair.