Rebuild an Outline Tree from Depth-Tagged Lines
Stacks & QueuesAuto-graded · 21 test casesLast updated
Turn a flat sequence of (depth, label) entries into a nested tree by attaching each entry to its nearest earlier entry with a smaller depth, using a monotonic stack.
Outline Tree Reconstruction
A document outline is stored as a flat, ordered sequence of entries. Each entry is a pair (depth, label), where depth is a positive integer and label is a string. Your job is to rebuild the hierarchy these entries describe.
Implement build_outline(entries), which returns the outline as a list of top-level nodes. Each node is a dictionary with exactly two keys:
"text": the entry's label (a string)"children": a list of child nodes, in the same format, in their original order
Attachment rules
Process the entries in the given order. For each entry with depth d:
- Look at the entries that appear before it and find the most recent one whose depth is strictly smaller than
d. - If such an entry exists, the current entry becomes the last child of that entry.
- If no such entry exists (for example, the sequence starts at depth
2, or the entry is at depth1), the current entry is a top-level node and is appended to the returned list. - Entries with equal depth are siblings, never parent and child.
- Depth jumps are allowed (e.g. from
1straight to3). Do not create filler nodes; the entry simply attaches to the nearest qualifying earlier entry. - Both the top-level list and every
childrenlist must keep the original input order.
Note that an earlier entry only counts as a candidate by the "most recent with a smaller depth" rule, so once a later entry with a depth less than or equal to it appears, it can no longer be reached as a parent by anything that follows that later entry in a way that would skip the later entry.
Input
entries: a list of[depth, label]pairs (integer, string).
Output
A list of nodes of the form {"text": str, "children": [...]}. Return [] for empty input.
Constraints
0 <= len(entries) <= 10^51 <= depth <= 10^4labelis a non-empty string of length at most100- Target time complexity:
O(N) - Target extra space:
O(N) - The nesting can be as deep as
N, so avoid relying on recursion.
Examples
Example 1
Input: build_outline([[1, 'Fruit'], [2, 'Apple'], [2, 'Banana'], [3, 'Cavendish'], [1, 'Vegetable']])
Output: [{'text': 'Fruit', 'children': [{'text': 'Apple', 'children': []}, {'text': 'Banana', 'children': [{'text': 'Cavendish', 'children': []}]}]}, {'text': 'Vegetable', 'children': []}]
Example 2
Input: build_outline([[1, 'Title'], [3, 'Deep note'], [2, 'Section']])
Output: [{'text': 'Title', 'children': [{'text': 'Deep note', 'children': []}, {'text': 'Section', 'children': []}]}]
Example 3
Input: build_outline([[2, 'Orphan'], [3, 'Child'], [1, 'Root'], [4, 'Deep']])
Output: [{'text': 'Orphan', 'children': [{'text': 'Child', 'children': []}]}, {'text': 'Root', 'children': [{'text': 'Deep', 'children': []}]}]
Hints
Hint 1
Think of the input as a pre-order walk of a tree where each entry's depth tells you how far down it sits. Which earlier entries could still be a parent of a future entry?
Hint 2
Keep a stack of (depth, node) pairs forming the current chain of possible parents. Before placing a new entry, discard stack items whose depth is greater than or equal to the new depth.
Hint 3
After popping, an empty stack means the entry is top-level; otherwise attach it to the node on top of the stack. Then push the new entry. Use >= when popping so equal depths become siblings.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The flat sequence is a pre-order traversal of a tree, with each entry's depth indicating its level. We rebuild the tree in a single pass using a stack that holds the current chain of candidate parents, each stored with its depth.
For each entry (depth, label):
- Create a new node
{"text": label, "children": []}. - Pop every stack item whose depth is
>= depth. Those items are siblings of the new entry (or descendants of siblings), so they cannot be its parent. - If the stack is now empty, the node is top-level; append it to the result list.
- Otherwise, append it to the
childrenof the node on top of the stack. - Push
(depth, node)onto the stack, since it may be the parent of later entries.
Why it is correct
After each step, the stack holds exactly the earlier nodes that could still be the nearest smaller-depth predecessor of a future entry, with depths strictly increasing from bottom to top.
- A stack item with depth
>= dcan never be the parent of the current entry. It also cannot be the parent of any later entry, because the current entry is more recent and has a depth no larger than that item's, so it would always win as the nearest candidate. Discarding it is therefore safe. - After popping, the top of the stack is the most recent earlier entry with a strictly smaller depth, which is exactly the parent required by the rules. An empty stack means no such entry exists, so the node is top-level.
- Nodes are appended in the order they are read, so ordering is preserved in both the top-level list and every
childrenlist. - Depth jumps need no special handling: the node just attaches to whatever is on top of the stack.
Complexity
- Time:
O(N). Every node is pushed once and popped at most once. - Space:
O(N)for the output tree and, in the worst case (strictly increasing depths), the stack.
The solution is iterative, so very deep nesting does not hit Python's recursion limit.
Reference solution
from typing import List, Tuple, Dict
def build_outline(entries: List[Tuple[int, str]]) -> List[Dict[str, object]]:
roots = []
stack = [] # (depth, node) chain of potential parents
for depth, label in entries:
node = {"text": label, "children": []}
# Remove entries that can never be the parent of this or later entries.
while stack and stack[-1][0] >= depth:
stack.pop()
if stack:
stack[-1][1]["children"].append(node)
else:
roots.append(node)
stack.append((depth, node))
return roots