Problem · Array

Render a Stable Comment Hierarchy

Learn this problem
MediumBobyard logoBobyardFULLTIMEPHONE SCREEN

Problem statement

You are given three parallel arrays describing comments in a flat collection:

  • ids[i] is the unique positive ID of comment i.
  • parentIds[i] is -1 when the comment is a root; otherwise it is the ID of another supplied comment.
  • texts[i] is the comment text.

The parent relationships form a valid acyclic forest. A parent may appear before or after its descendants.

Return the comments in depth-first preorder. Preserve input order among roots and among children of the same parent. Prefix each text with two spaces for every level of depth.

Function

renderComments(ids: int[], parentIds: int[], texts: String[]) → String[]

Examples

Example 1

ids = [10,20,30,40,50]parentIds = [-1,10,10,20,-1]texts = ["Root A","Reply A1","Reply A2","Deep reply","Root B"]return = ["Root A","  Reply A1","    Deep reply","  Reply A2","Root B"]

The first root is followed by its descendants in stable input order. The second root appears last.

Example 2

ids = [4,2,1,3]parentIds = [2,1,-1,1]texts = ["grandchild","first child","root","second child"]return = ["root","  first child","    grandchild","  second child"]

Parents may appear after their descendants in the input. The output still follows the hierarchy.

Example 3

ids = [7,8,9]parentIds = [-1,-1,-1]texts = ["one","two","three"]return = ["one","two","three"]

All comments are roots, so no indentation is added and input order is preserved.

Constraints

  • 1 <= ids.length == parentIds.length == texts.length <= 100000
  • 1 <= ids[i] <= 1000000000, and all IDs are unique.
  • parentIds[i] is -1 or an ID present in ids.
  • The parent relation is acyclic.
  • texts[i] is nonempty and contains at most 100 printable characters.
drafts saved locally
public String[] renderComments(int[] ids, int[] parentIds, String[] texts) {
    // Write your code here.
}
ids[10,20,30,40,50]
parentIds[-1,10,10,20,-1]
texts["Root A","Reply A1","Reply A2","Deep reply","Root B"]
expected["Root A", "Reply A1", "Deep reply", "Reply A2", "Root B"]
checking account