Flatten a Multilevel Doubly Linked List - Problem

You are given a doubly linked list that contains nodes with a next pointer, a prev pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, which also contains these special nodes. These child lists may have one or more children of their own, creating a multilevel data structure.

Given the head of the first level of the list, flatten the list so that all nodes appear in a single-level, doubly linked list. The nodes in the child list should appear after the current node and before the current node's next node in the flattened list.

Return the head of the flattened list. All child pointers must be set to null.

Input & Output

Example 1 — Simple Multilevel
$ Input: head = [1,2,3,null,null,7,8,null,null,null,null]
Output: [1,2,7,8,3]
💡 Note: Node 2 has child 7→8. After flattening: 1→2→7→8→3 with all child pointers set to null
Example 2 — Single Level
$ Input: head = [1,2,3,4,5]
Output: [1,2,3,4,5]
💡 Note: No child nodes exist, so the list remains unchanged: 1→2→3→4→5
Example 3 — Empty List
$ Input: head = null
Output: null
💡 Note: Empty list returns null

Constraints

  • The number of Nodes will not exceed 1000
  • 1 ≤ Node.val ≤ 105

Visualization

Tap to expand
INPUTALGORITHMRESULT12378Multilevel StructureChild at node 21Find Child Node2Connect Child Branch3Clear Child Pointers4Continue TraversalDFS ApproachTime: O(n)Space: O(1)12783Flattened ListSingle level doubly linkedAll child pointers = nullKey Insight:When you encounter a child branch, connect it immediately into the main chainand continue traversal to handle nested children recursively.TutorialsPoint - Flatten a Multilevel Doubly Linked List | DFS with Stack
Asked in
Amazon 45 Microsoft 32 LinkedIn 28 Google 22
124.5K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen