Rebuild a Nested Menu Tree from Indented Text
Trees & GraphsAuto-graded · 22 test casesLast updated
Parse an indentation-based, pipe-delimited menu into a nested tree of dictionaries, testing stack-based hierarchy reconstruction and careful field parsing.
Rebuild a Nested Menu Tree from Indented Text
A kitchen system exports its menu as plain text. Each line is one entry, and the indentation shows which entry is nested inside which. Your job is to turn that text into a nested structure.
Line format
Every non-blank line looks like this:
<indent><type>|<id>|<name>|<price>
<indent>is zero or more repetitions of exactly two space characters. Each pair of spaces is one level of depth. A line with no leading spaces has depth 0 and is a top-level entry.- The four fields are separated by
|. typeis an arbitrary non-empty string. Do not treat any particular value specially.idis a non-empty identifier string.nameis free text that never contains|. Keep it exactly as written.priceis either a decimal number such as5.99or the single character-, meaning "no price".
An entry at depth d (with d > 0) is a child of the most recent preceding entry at depth d - 1. Children keep the order in which they appear in the text.
Task
Implement a function that receives the menu text and returns a list of the top-level entries, in order. Each entry is a dictionary with exactly these keys:
| key | value |
|---|---|
"type" | the type string |
"id" | the id string |
"name" | the name string |
"price" | None if the price field is -, otherwise the price converted to a number (float) |
"children" | a list of the entry's child dictionaries in the same format (empty list if none) |
Rules
- Lines that are empty or contain only whitespace are ignored.
- Lines are separated by newline characters; there may or may not be a trailing newline.
- The input is always valid, so you do not need to handle malformed lines.
Constraints
- The number of entries
Nsatisfies1 <= N, and the solution should run inO(N)time andO(N)extra space. - Indentation always consists of whole pairs of spaces, with no tabs.
- When going deeper, depth increases by at most one from one entry to the next; it may drop by any amount.
- The first entry is at depth 0.
namenever contains|, andtypeandidare non-empty.- A numeric price is a valid decimal literal (for example
0.00,1.50,12).
Examples
Example 1
Input: parse_menu_tree('CATEGORY|c1|Burgers|-\n FOOD|f1|Classic Burger|5.99\n SIDE|s1|Fries|1.99\n FOOD|f2|Veggie Burger|6.49\nCATEGORY|c2|Drinks|-\n FOOD|f3|Cola|1.50\n FOOD|f4|Water|1.00')
Output: [{'type': 'CATEGORY', 'id': 'c1', 'name': 'Burgers', 'price': None, 'children': [{'type': 'FOOD', 'id': 'f1', 'name': 'Classic Burger', 'price': 5.99, 'children': []}, {'type': 'SIDE', 'id': 's1', 'name': 'Fries', 'price': 1.99, 'children': []}, {'type': 'FOOD', 'id': 'f2', 'name': 'Veggie Burger', 'price': 6.49, 'children': []}]}, {'type': 'CATEGORY', 'id': 'c2', 'name': 'Drinks', 'price': None, 'children': [{'type': 'FOOD', 'id': 'f3', 'name': 'Cola', 'price': 1.5, 'children': []}, {'type': 'FOOD', 'id': 'f4', 'name': 'Water', 'price': 1, 'children': []}]}]
Example 2
Input: parse_menu_tree('ROOT|r1|Menu|-\n CATEGORY|c1|Main|-\n ITEM|i1|Special|0.00\n CATEGORY|c2|Sides|-')
Output: [{'type': 'ROOT', 'id': 'r1', 'name': 'Menu', 'price': None, 'children': [{'type': 'CATEGORY', 'id': 'c1', 'name': 'Main', 'price': None, 'children': [{'type': 'ITEM', 'id': 'i1', 'name': 'Special', 'price': 0, 'children': []}]}, {'type': 'CATEGORY', 'id': 'c2', 'name': 'Sides', 'price': None, 'children': []}]}]
Example 3
Input: parse_menu_tree('CATEGORY|c1|Burgers|-')
Output: [{'type': 'CATEGORY', 'id': 'c1', 'name': 'Burgers', 'price': None, 'children': []}]
Hints
Hint 1
Compute each line's depth from the number of leading spaces divided by two, then split the rest of the line on the pipe character.
Hint 2
Keep a stack that holds the chain of ancestors of the current line. Before placing a new entry at depth d, cut the stack back to length d. The new entry's parent is then the top of the stack.
Hint 3
If depth is 0, append the entry to the result list. Otherwise append it to its parent's children, then push it on the stack. Don't slice the stack into a new list each time; deleting the tail keeps the total work linear.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process the text one line at a time while maintaining a stack that holds the chain of ancestors of the line currently being read. stack[i] is the most recent entry seen at depth i.
For each non-blank line:
- Count the leading spaces. The depth is that count divided by two.
- Split the remainder on
|into type, id, name and price text. The price isNonefor-, otherwisefloat(price_text). - Build a node dictionary with an empty
childrenlist. - Trim the stack to length
depth(del stack[depth:]). Everything left on the stack is an ancestor of the new line, and the top is its direct parent, which is the latest entry at depthdepth - 1. - If
depth == 0, append the node to the result list. Otherwise append it tostack[-1]["children"]. - Push the node onto the stack so that following deeper lines can attach to it.
Why it is correct
Because depth increases by at most one between consecutive entries, the stack always has at least depth elements when a line at that depth arrives, so the parent exists. After trimming, the top of the stack is exactly the most recent entry at depth depth - 1, which is the definition of the parent. Entries are appended in input order, so every children list preserves the original order. Type is never inspected, so any type string works. Name is taken verbatim from the field, so internal spaces are preserved.
Complexity
Each line is pushed once and popped at most once, so the total stack work is O(N). Splitting and converting fields is linear in the text length. Overall time is O(N) (in terms of text size) and extra space is O(N) for the tree plus up to O(depth) for the stack. There is no recursion, so deep menus cannot overflow the call stack.
Reference solution
from typing import List, Dict
def parse_menu_tree(text: str) -> List[Dict]:
roots: List[Dict] = []
stack: List[Dict] = [] # ancestors of the current line, shallowest first
for line in text.splitlines():
if not line.strip():
continue
indent = len(line) - len(line.lstrip(' '))
depth = indent // 2
item_type, item_id, name, price_text = line[indent:].split('|')
price = None if price_text == '-' else float(price_text)
node = {
'type': item_type,
'id': item_id,
'name': name,
'price': price,
'children': [],
}
# Discard ancestors that are as deep as or deeper than this line.
del stack[depth:]
if depth == 0:
roots.append(node)
else:
stack[-1]['children'].append(node)
stack.append(node)
return roots