call(back)

Build a Comment Tree From Flat Records

An API returns comments as a flat list. Each comment is { id, parent_id, text }, and a parent_id of null marks a top-level comment. Implement buildCommentTree(comments), which returns the top-level comments as an array, each with its replies nested inside it to any depth.

  • Every comment in the output keeps its id, parent_id and text and gains a children array, empty when it has no replies.
  • Top-level comments, and the replies inside each children array, appear in the order they have in the input.
  • A reply may appear in the input before the comment it answers.
  • A comment whose parent_id matches no comment is treated as top-level.
  • Do not mutate the input objects.
buildCommentTree([
  { id: 1, parent_id: null, text: "First root" },
  { id: 2, parent_id: null, text: "Second root" },
  { id: 3, parent_id: 1, text: "Reply to the first root" },
  { id: 4, parent_id: 2, text: "Reply to the second root" },
  { id: 5, parent_id: 3, text: "Reply to the reply" },
]);
// root 1 contains 3, which contains 5; root 2 contains 4

Ids are unique. The interviewer's own example had a typo in one parent_id; ask about anything in sample data that does not add up.

Hints

Hint 1

Finding a comment's parent by scanning the list makes the whole thing quadratic. Index the comments by id first.

Hint 2

Two passes: create a copy of every comment with an empty children array and store it in a map; then attach each copy to its parent's children, or to the roots.

Hint 3

Because every node exists before any attaching happens, the order of the input does not matter.

Asked at

Similar Problems6