Bird
Raised Fist0
Interview Prepcustom-data-structuresmediumAmazonMicrosoftGoogle

Flatten a Multilevel Doubly Linked List

Choose your preparation mode3 modes available
Steps
setup

Initialize traversal at head node 1

Start with the head node (value 1). The current pointer is set to node 1, and the stack shows the traversal starting point.

💡 Initialization sets the starting point for flattening, making clear where the algorithm begins.
Line:curr = head
💡 The algorithm begins traversal from the head node, preparing to scan for child pointers.
📊
Flatten a Multilevel Doubly Linked List - Watch the Algorithm Execute, Step by Step
Watching each pointer update and child list integration step-by-step reveals how the algorithm maintains list integrity while flattening, which is hard to grasp from code alone.
Step 1/19
·Active fillAnswer cell
no_opElement[0]: 1
Stack (top→bottom)
1
no_opElement[1]: 2
Stack (top→bottom)
2
1
peekElement[2]: 3
Stack (top→bottom)
3
2
1
no_opElement[2]: 3
Stack (top→bottom)
3
2
1
Contributes: "Tail found at node 10"
no_opElement[2]: 3
Stack (top→bottom)
3
2
1
Contributes: "Tail node 10 connected to node 4"
pushElement[2]: 3
Stack (top→bottom)
7
3
2
1
↑ pushed: 7
Contributes: "Child list spliced after node 3"
no_opElement[3]: 7
Stack (top→bottom)
7
3
2
1
peekElement[4]: 8
Stack (top→bottom)
8
7
3
2
1
no_opElement[4]: 8
Stack (top→bottom)
8
7
3
2
1
Contributes: "Tail found at node 12"
no_opElement[4]: 8
Stack (top→bottom)
8
7
3
2
1
Contributes: "Tail node 12 connected to node 9"
pushElement[4]: 8
Stack (top→bottom)
11
8
7
3
2
1
↑ pushed: 11
Contributes: "Nested child list spliced after node 8"
no_opElement[5]: 11
Stack (top→bottom)
11
8
7
3
2
1
no_opElement[6]: 12
Stack (top→bottom)
12
11
8
7
3
2
1
no_opElement[7]: 9
Stack (top→bottom)
9
12
11
8
7
3
2
1
no_opElement[8]: 10
Stack (top→bottom)
10
9
12
11
8
7
3
2
1
no_opElement[9]: 4
Stack (top→bottom)
4
10
9
12
11
8
7
3
2
1
no_opElement[10]: 5
Stack (top→bottom)
5
4
10
9
12
11
8
7
3
2
1
no_opElement[11]: 6
Stack (top→bottom)
6
5
4
10
9
12
11
8
7
3
2
1
no_op
Stack (top→bottom)
6
5
4
10
9
12
11
8
7
3
2
1
Contributes: "Flattened list head returned"

Key Takeaways

Flattening is done in-place by splicing child lists directly into the main list without extra memory.

This insight is hard to see from code alone because pointer updates are subtle and interdependent.

Finding the tail of the child list before splicing is crucial to reconnect the flattened list correctly.

Visualizing the tail traversal clarifies why this step is necessary to avoid losing nodes.

Child pointers are removed immediately after splicing to prevent reprocessing and mark progress.

Seeing the child pointer cleared in the trace shows how the algorithm avoids infinite loops.