#430

Flatten a Multilevel Doubly Linked List

Medium
Linked ListDepth-First SearchDoubly-Linked ListDepth-First SearchStack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a depth-first search (DFS) technique to flatten the list in a single pass. This method efficiently handles the child pointers while maintaining the order of nodes.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a stack and push the head node onto it.
  2. 2Step 2: While the stack is not empty, pop the top node.
  3. 3Step 3: If the node has a next node, push it onto the stack.
  4. 4Step 4: If the node has a child, push the child onto the stack and set the child pointer to null.
  5. 5Step 5: Link the current node to the previous node.
solution.py26 lines
1# Full working Python code
2class Node:
3    def __init__(self, val=0, prev=None, next=None, child=None):
4        self.val = val
5        self.prev = prev
6        self.next = next
7        self.child = child
8
9class Solution:
10    def flatten(self, head: 'Node') -> 'Node':
11        if not head:
12            return head
13        stack = [head]
14        prev = None
15        while stack:
16            curr = stack.pop()
17            if prev:
18                prev.next = curr
19                curr.prev = prev
20            if curr.next:
21                stack.append(curr.next)
22            if curr.child:
23                stack.append(curr.child)
24                curr.child = None
25            prev = curr
26        return head

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the stack used for DFS, which can store all nodes in the worst case.

  • 1DFS is a powerful technique for tree-like structures.
  • 2Using a stack allows us to manage the nodes efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.