Problem · Array

Render a Comment Hierarchy

MediumAmazon logoAmazonNEW GRADONSITE INTERVIEW
See Amazon hiring insights

Problem statement

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

  • ids[i] is the unique ID of comment i.
  • parentIds[i] is -1 when comment i is a root; otherwise it is the ID of that comment's parent.
  • texts[i] is the comment text.

The parent relationships form a valid acyclic forest and may have arbitrary depth. A parent may appear before or after its children in the input.

The problem statement continues
Pro

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 children in input order. The child of Reply A1 has depth two, so it receives four leading spaces. The second root is rendered last.

FastPrep Pro
Reported in 1 Amazon interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 2 more worked examples, explained
  • Guided hints and editorial
  • Run your code on real test cases
$9/month

Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week
CodePython 3
Run and Submit unlock with Pro
FastPrep Pro
Reported in 1 Amazon interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 2 more worked examples, explained
  • Guided hints and editorial
  • Run your code on real test cases
$9/month

Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week