766. Flatten a Multilevel Doubly Linked List
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to flatten a multilevel doubly linked list. This special kind of linked list has next and prev pointers, but also a child pointer that can point to a separate doubly linked list. When we flatten the list, if a node curr has a child list, this entire child list must be inserted between curr and curr.next. This process needs to be applied to all nodes with children, effectively merging all levels into a single-level doubly linked list. Finally, all child pointers in the resulting list must be set to null.
Solution
Flatten a Multilevel Doubly Linked List in Python
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head:
return None
# Dummy node to simplify list construction.
pseudo_head = Node(0, None, None, None)
prev_node = pseudo_head
stack = [head]
while stack:
curr_node = stack.pop()
# Link previous node with current node.
prev_node.next = curr_node
curr_node.prev = prev_node
# Push next and child to the stack.
# Push next first, so child is processed first (LIFO).
if curr_node.next:
stack.append(curr_node.next)
if curr_node.child:
stack.append(curr_node.child)
# Set child to null as required by the problem.
curr_node.child = None
# Move prev_node pointer forward for the next iteration.
prev_node = curr_node
# Detach the pseudo head from the flattened list.
new_head = pseudo_head.next
if new_head:
new_head.prev = None
return new_head
Flatten a Multilevel Doubly Linked List in Java
/*
// Definition for a Node.
class Node {
public int val;
public Node prev;
public Node next;
public Node child;
};
*/
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public Node flatten(Node head) {
if (head == null) {
return null;
}
// Dummy node to simplify list construction.
Node pseudoHead = new Node();
Node prev = pseudoHead;
// Use Deque as a stack.
Deque<Node> stack = new ArrayDeque<>();
stack.push(head);
while (!stack.isEmpty()) {
Node curr = stack.pop();
// Link previous node with current node.
prev.next = curr;
curr.prev = prev;
// Push next and child to the stack.
// Push next first, so child is processed first (LIFO).
if (curr.next != null) {
stack.push(curr.next);
}
if (curr.child != null) {
stack.push(curr.child);
// Set child to null as required by the problem.
curr.child = null;
}
// Move prev pointer forward for the next iteration.
prev = curr;
}
// Detach the pseudo head from the flattened list.
Node newHead = pseudoHead.next;
if (newHead != null) {
newHead.prev = null;
}
return newHead;
}
}
Flatten a Multilevel Doubly Linked List in C++
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
#include <stack>
class Solution {
public:
Node* flatten(Node* head) {
if (!head) {
return nullptr;
}
// A dummy node to simplify list construction.
// Assuming Node has a default constructor or LeetCode environment allows this.
Node* pseudoHead = new Node();
Node* prev = pseudoHead;
std::stack<Node*> s;
s.push(head);
while (!s.empty()) {
Node* curr = s.top();
s.pop();
// Link previous node with current node
prev->next = curr;
curr->prev = prev;
// Push next and child to the stack.
// Push next first, so child is processed first (LIFO).
if (curr->next) {
s.push(curr->next);
}
if (curr->child) {
s.push(curr->child);
// Set child to null as required by the problem.
curr->child = nullptr;
}
// Move prev pointer forward for the next iteration.
prev = curr;
}
// Detach the pseudo head from the flattened list.
Node* newHead = pseudoHead->next;
if (newHead) {
newHead->prev = nullptr;
}
delete pseudoHead; // Clean up the dynamically allocated dummy node.
return newHead;
}
};
Flatten a Multilevel Doubly Linked List in TypeScript
/**
* Definition for _Node.
* class _Node {
* val: number
* prev: _Node | null
* next: _Node | null
* child: _Node | null
*
* constructor(val?: number, prev? : _Node, next? : _Node, child? : _Node) {
* this.val = (val===undefined ? 0 : val);
* this.prev = (prev===undefined ? null : prev);
* this.next = (next===undefined ? null : next);
* this.child = (child===undefined ? null : child);
* }
* }
*/
function flatten(head: _Node | null): _Node | null {
if (!head) {
return null;
}
// Dummy node to simplify list construction.
const pseudoHead = new _Node(0, null, null, null);
let prev: _Node = pseudoHead;
const stack: _Node[] = [head];
while (stack.length > 0) {
const curr = stack.pop()!;
// Link previous node with current node.
prev.next = curr;
curr.prev = prev;
// Push next and child to the stack.
// Push next first, so child is processed first (LIFO).
if (curr.next) {
stack.push(curr.next);
}
if (curr.child) {
stack.push(curr.child);
// Set child to null as required by the problem.
curr.child = null;
}
// Move prev pointer forward for the next iteration.
prev = curr;
}
// Detach the pseudo head from the flattened list.
const newHead = pseudoHead.next!;
newHead.prev = null;
return newHead;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.