Convert Multi-Level Branching List to Doubly Linked List
Linked ListsAuto-graded · 23 test casesLast updated
Flatten a tree-like linked structure with main and side links into a single doubly linked sequence using preorder traversal.
You are given a linked structure containing $n$ nodes indexed from $0$ to $n - 1$. Node 0 serves as the entry point. Each node i can have two outgoing pointers:
next_node[i]: the next node in the current sequence, or-1if nodeiis the last element of its sequence.branch[i]: the head node of an attached side sublist, or-1if nodeidoes not have a side sublist.
Side sublists can themselves contain further side sublists. The overall structure forms a valid tree-like topology without cycles or shared nodes, starting at node 0.
Your task is to flatten this multi-level structure into a single doubly linked sequence according to the following order:
- Every node
imust be immediately followed by the complete flattened content of its side branch (if one exists). - Following the side branch, the flattened sequence continues with the remaining nodes that originally followed node
ivianext_node.
After flattening, all side branches are removed, and nodes are connected exclusively by forward and backward links.
Return the flattened doubly linked list represented as a pair of arrays [forward_links, backward_links], each of length $n$:
forward_links[i]is the node that comes immediately after nodeiin the flattened order (-1ifiis the final node).backward_links[i]is the node that comes immediately before nodeiin the flattened order (-1ifiis the starting node0).
Constraints
- $1 \le n \le 100,000$, where $n = \text{len}(\text{next_node}) = \text{len}(\text{branch})$
- $-1 \le \text{next_node}[i] \le n - 1$ and $-1 \le \text{branch}[i] \le n - 1$ for all $0 \le i < n$
- Node
0has no incoming links. Every other node $1 \le i < n$ is pointed to by exactly one entry acrossnext_nodeandbranch. - Every node is reachable from node
0. - Nesting depth of branches or long
next_nodechains can reach up to $n - 1$. - The output structure is uniquely determined.
Examples
Example 1
Input: flatten_with_branches([1, 2, -1], [-1, -1, -1])
Output: [[1, 2, -1], [-1, 0, 1]]
Example 2
Input: flatten_with_branches([1, 2, -1, 4, -1, -1], [-1, 3, -1, 5, -1, -1])
Output: [[1, 3, -1, 5, 2, 4], [-1, 0, 4, 1, 5, 3]]
Example 3
Input: flatten_with_branches([1, -1, 3, -1], [-1, 2, -1, -1])
Output: [[1, 2, 3, -1], [-1, 0, 1, 2]]
Hints
Hint 1
View the node structure as a binary tree where 'branch' acts as the left child and 'next_node' acts as the right child.
Hint 2
What tree traversal order visits the root, then the left subtree, then the right subtree?
Hint 3
Because nesting and chain length can reach up to 100,000, recursion might cause a stack overflow in Python. How can you implement this iteratively?
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key observation is that the structural layout matches a binary tree:
- Node
0is the root of the tree. branch[u]represents the left child (the subtree that should be processed immediately afteru).next_node[u]represents the right child (the continuation after the branch finishes).
The requirement specifies that a node u must be followed first by the flattened content of its branch sublist, and then by the flattened content of its next_node chain. In tree terms, this sequence is Node $\rightarrow$ Left Subtree $\rightarrow$ Right Subtree, which corresponds precisely to a preorder traversal.
Because $n$ can be up to $100,000$, a recursive traversal could trigger a stack overflow in Python due to deep recursion limits. An explicit stack should be used instead:
- Initialize a stack containing the starting node
0and keep track ofprev = -1. - Pop the top element
currfrom the stack. - If
previs valid (not-1), establish the forward and backward connections: setforward_links[prev] = currandbackward_links[curr] = prev. - Update
prev = curr. - To process the left child (
branch) before the right child (next_node), pushnext_node[curr]onto the stack first, followed bybranch[curr](since a LIFO stack pops the most recently pushed item first). - Repeat until the stack is empty.
Complexity Analysis
- Time Complexity: $\mathcal{O}(n)$. Every node is pushed and popped from the stack exactly once, performing constant time $\mathcal{O}(1)$ operations per node.
- Space Complexity: $\mathcal{O}(n)$. The stack holds at most $\mathcal{O}(n)$ items in the worst case (e.g., a straight chain of nodes with both next and branch children), and the output arrays each take $\mathcal{O}(n)$ space.
Python Reference Solution
def flatten_with_branches(next_node: list[int], branch: list[int]) -> list[list[int]]:
n = len(next_node)
fwd = [-1] * n
back = [-1] * n
stack = [0]
prev = -1
while stack:
curr = stack.pop()
if prev != -1:
fwd[prev] = curr
back[curr] = prev
prev = curr
# Push next_node first so branch is popped and processed first (LIFO order)
if next_node[curr] != -1:
stack.append(next_node[curr])
if branch[curr] != -1:
stack.append(branch[curr])
return [fwd, back]