← Questions

Block tree with add, delete subtree and render

0
NotionCodingLast asked Jul 2025

A coding interview question asked in Notion's practical coding and debugging round, last asked Jul 2025. It tests trees, dfs and design.

A document is an ordered forest of blocks. Each block has an id and some text, and it is either top level or the child of another block. Process a list of operations that add blocks, delete a block with everything under it, and render the document.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • process(operations: list[list[str]]) -> list[str] — returns the output of every RENDER, in order.
  • ["ADD", id, parent_id, text] adds a block as the last child of parent_id, or as the last top-level block when parent_id is "-".
  • ["DELETE", id] removes the block and every block nested under it.
  • ["RENDER"] lists every block in pre-order, one line per block as depth|id|text (top level is depth 0), siblings in the order they were added, lines joined by "\n".

Example

["ADD", "a", "-", "Page"]
["ADD", "b", "a", "Heading"]
["ADD", "c", "a", "Paragraph"]
["ADD", "d", "b", "Text"]
["RENDER"]       -> "0|a|Page\n1|b|Heading\n2|d|Text\n1|c|Paragraph"
["DELETE", "b"]  # d goes with it
["RENDER"]       -> "0|a|Page\n1|c|Paragraph"

Constraints

  • 1 <= len(operations) <= 20000; at most 200,000 rendered lines in total.
  • Ids are unique and never reused, even after a delete. A parent exists when its child is added; a deleted id exists.
  • Ids and text contain no |, ids no whitespace, text no newline.

Clarifying questions

  • Must sibling order be insertion order, or can blocks be inserted at a position?
  • After a delete, can a later ADD name a deleted block as its parent?
  • How deep can the tree get (recursion limits)?
  • How often is RENDER called compared with edits?

What a strong answer covers

  • A map from id to block (text, parent, ordered children) and an ordered list of top-level ids.
  • Delete in O(1) for the unlink by removing the block from its parent's children (an ordered dict or a linked list keeps that O(1)), leaving descendants unreachable, or freeing the subtree explicitly to reclaim memory.
  • Pre-order rendering with an explicit stack, pushing children in reverse, in time linear in the output.
  • Tests: deleting a top-level block, deleting a leaf, a deep chain, rendering an empty document.

Follow-ups

  • Add MOVE id new_parent position, and refuse a move under the block's own descendant.
  • Add UNDO for the last add or delete, restoring a deleted subtree in its original place.
  • Render only the subtree under a given block, or only up to a given depth.

Where it's asked

What it tests

trees · dfs · design

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding