What does each node of the list contain?
Each node contains an integer value, a next
pointer to the next node, a prev
pointer to the previous node, and a child
pointer to a potentially nested doubly linked list.
next
node.child
pointers should be removed.child
pointer, we’ll need to flatten that part first.next
nodes.child
, append the child list between the current node and the next.The time complexity of this approach is (O(n)), where (n) is the total number of nodes in the list including all depths. This is because we are processing each node exactly once.
Below is a Python implementation of the solution:
# Node definition
class Node:
def __init__(self, val: int, prev: 'Node' = None, next: 'Node' = None, child: 'Node' = None):
self.val = val
self.prev = prev
self.next = next
self.child = child
def flatten(head: 'Node') -> 'Node':
if not head:
return head
# Create a pseudo head that allows to deal with edge cases easily
pseudo_head = Node(0, None, head, None)
prev = pseudo_head
stack = []
stack.append(head)
while stack:
curr = stack.pop()
prev.next = curr
curr.prev = prev
# If we find a next node, add it to the stack
if curr.next:
stack.append(curr.next)
# If we find a child node, add it to the stack
if curr.child:
stack.append(curr.child)
curr.child = None # Don't forget to remove the child reference
prev = curr
# Detach the pseudo head
pseudo_head.next.prev = None
return pseudo_head.next
pseudo_head
to simplify handling edge cases (like empty list or single node list).next
and prev
pointers while preserving child
nodes into the flattened list.This approach ensures that all nodes are visited precisely once, making it efficient with (O(n)) time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?