Assemble a Reply Thread Forest from Flat Records
Trees & GraphsAuto-graded · 15 test casesLast updated
Convert an unordered flat list of records with parent links into a nested forest, preserving input order and rejecting duplicate ids, missing parents and cycles.
Reply Thread Forest
You are given a flat list of discussion posts. Each post is a dictionary with an id and, optionally, other fields such as text, plus a parent_id that is either the id of the post it replies to or None for a top-level post. Posts can appear in any order, so a reply may come before the post it replies to.
Write a function that converts this list into a forest of nested posts and returns the list of top-level posts.
Output format
- Each output post is a copy of the input dictionary with every original field kept, plus a new key
children. Its value is a list of the output posts that reply directly to it. - Children appear in the same relative order as they do in the input list.
- The returned list holds the top-level posts (those whose
parent_idisNone, or whoseparent_idkey is missing), also in input order. - The input dictionaries must not be modified.
- An
idorparent_idof0is a real id. OnlyNonemeans "no parent".
Invalid input
Raise ValueError in these situations:
- Two posts share the same
id. - A post's
parent_idis notNoneand does not match theidof any post in the list (a dangling reference). - The parent links form a cycle, including a post that is its own parent. Such posts would otherwise never be reachable from any top-level post.
If the input has several problems, check in this order: duplicate ids, then dangling references, then cycles.
An empty list returns an empty list.
Constraints
- The number of posts N satisfies
0 <= N <= 10^5. - Aim for
O(N)time. - Threads can be very deep (thousands of levels), so avoid recursion in your construction and validation.
- Ids are hashable values (typically integers).
Examples
Example 1
Input: build_reply_forest([{'id': 2, 'parent_id': 1}, {'id': 1, 'parent_id': None}, {'id': 3, 'parent_id': 1}])
Output: [{'id': 1, 'parent_id': None, 'children': [{'id': 2, 'parent_id': 1, 'children': []}, {'id': 3, 'parent_id': 1, 'children': []}]}]
Example 2
Input: build_reply_forest([{'id': 1, 'text': 'A', 'parent_id': None}, {'id': 2, 'text': 'B', 'parent_id': 1}, {'id': 3, 'text': 'C', 'parent_id': 2}])
Output: [{'id': 1, 'text': 'A', 'parent_id': None, 'children': [{'id': 2, 'text': 'B', 'parent_id': 1, 'children': [{'id': 3, 'text': 'C', 'parent_id': 2, 'children': []}]}]}]
Hints
Hint 1
Create an output node for every post before linking anything, so a reply that appears before its parent causes no trouble.
Hint 2
After indexing, loop over the input in order and append each node to its parent's children list (or to the roots list). This keeps sibling order the same as in the input.
Hint 3
Each post has at most one parent, so cycles can be found by walking up parent links with three states (unvisited, on current walk, known safe). Do this iteratively; reaching a node that is on the current walk means a cycle.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each post points up to its parent, but the output needs links going down to children. We reverse the links in three linear passes.
- Index pass. Create an output node for every post (a shallow copy plus an empty
childrenlist) and store it in a hash map keyed byid. Also record each post's parent id. If an id is already in the map, raiseValueError. Because all nodes exist before any linking, the order of arrival does not matter. - Link pass. Go through the input in its original order. If the parent is
None, the node is a root. If the parent id is not in the map, raiseValueErrorfor a dangling reference. Otherwise append the node to its parent'schildren. Iterating in input order keeps both sibling order and root order. - Cycle pass. Every node has at most one parent, so a cycle exists exactly when walking up from some node comes back to a node on the current walk. Use three states: 0 unvisited, 1 on the current walk, 2 known to reach a root. Walk upward from each unvisited node, marking nodes as 1. If the walk hits a state-1 node, raise
ValueError. If it ends atNoneor a state-2 node, mark the whole path as 2.
Why it is correct
- Each post is appended to exactly one place (a parent's list or the root list), so the structure contains every post exactly once, provided no cycle exists.
- Nodes on a cycle have valid parents, so the dangling check passes them, yet they would never be reachable from a root and would vanish silently. The cycle pass catches this, including self-parents.
- A walk that reaches a state-2 node can stop, since that node is already proven to reach a root.
- Checking
is Nonerather than truthiness keeps id0valid. - The check order (duplicates, dangling, cycles) follows from the pass order.
Complexity
- Time: O(N). Index and link passes are single loops with O(1) hash operations. In the cycle pass each node moves from state 0 to 1 and then to 2 once, so the total walking is O(N).
- Space: O(N) for the node map, parent map, state map and path buffer.
- The validation is iterative, so very deep threads cannot overflow the call stack.
Reference solution
from typing import List, Dict
def build_reply_forest(posts: List[Dict]) -> List[Dict]:
nodes = {}
parent_of = {}
roots = []
for post in posts:
pid_key = post['id']
if pid_key in nodes:
raise ValueError('Duplicate comment id')
node = dict(post)
node['children'] = []
nodes[pid_key] = node
parent_of[pid_key] = post.get('parent_id')
for post in posts:
cid = post['id']
pid = parent_of[cid]
if pid is None:
roots.append(nodes[cid])
elif pid not in nodes:
raise ValueError('Dangling parent reference')
else:
nodes[pid]['children'].append(nodes[cid])
state = {}
for cid in nodes:
if state.get(cid, 0) != 0:
continue
path = []
current = cid
while current is not None and state.get(current, 0) == 0:
state[current] = 1
path.append(current)
current = parent_of[current]
if current is not None and state.get(current) == 1:
raise ValueError('Circular dependency detected')
for node_id in path:
state[node_id] = 2
return roots