Katkat

Build Nested Comments from Parent References

BobyardSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to handle tree data structures, pointer manipulation, and graph validation while processing unordered flat data.

Problem Statement

You are given a list of comments, where each comment contains an id, text, and an optional parent_id. Comments may arrive in any order; it is possible for a child comment to appear in the input before its parent.

Your task is to transform this flat list into a hierarchical forest structure. A parent node should contain a list of its children in the order they appear in the original input. You must also implement basic validation to return an error if a comment refers to a non-existent parent_id (a dangling reference) or if a circular dependency is detected.

Function Signature

def build_comment_tree(comments):
    # comments: List of dicts, e.g., {'id': 1, 'text': 'A', 'parent_id': None}
    # Returns: List of root nodes with nested 'children' lists
    # Raises: ValueError for dangling references or cycles

Examples

Example 1: Input: [{'id': 2, 'parent_id': 1}, {'id': 1, 'parent_id': None}, {'id': 3, 'parent_id': 1}] Output: [{'id': 1, 'parent_id': None, 'children': [{'id': 2, 'children': []}, {'id': 3, 'children': []}]}]

Example 2 (Dangling): Input: [{'id': 2, 'parent_id': 99}] Output: Raises ValueError because 99 does not exist.

Constraints

  • Number of comments: N <= 10^5.
  • You must process the data in linear time O(N).
  • Preserve the relative order of children as found in the input list.

Hints

Hint 1

Use a hash map to store references to all comment objects by their ID for O(1) lookup during tree construction.

Hint 2

First, create a placeholder object for every comment to handle children appearing before parents; then, make a second pass to link them to their respective parents.

Hint 3

To detect cycles, perform a depth-first search or track nodes visited during the parent-linking phase to ensure you never traverse back to a node currently in the recursion stack.

Follow-up questions

  • How would you modify your approach to handle updates to the comment tree, such as moving a comment to a new parent?
  • If the thread is extremely deep (e.g., 10,000 levels), how would you optimize the memory usage and avoid stack overflow errors?
  • How would you represent this structure in a relational database versus a document-oriented database to support efficient retrieval of nested branches?