Skip to content
RED SAGSkills

Build a Threaded Comment Tree

A discussion API returns comments as a flat list of { id, parentId, author, ts }, where parentId is null for a top-level comment. Build the nested thread for the UI.

Each output node is { id, author, replies }, where replies holds its child nodes. A comment whose parentId does not match any comment (its parent was deleted) is shown as a top-level comment. At every level, siblings are ordered by ts ascending, then by id ascending (plain string order).

Return the array of top-level nodes.

Example 1

Input: comments = [{"id":"c3","parentId":"c1","author":"zed","ts":30},{"id":"c1","parentId":null,"author":"ana","ts":10},{"id":"c2","parentId":"c1","author":"bo","ts":20},{"id":"c4","parentId":"gone","author":"cy","ts":5}]
Output: [{"id":"c4","author":"cy","replies":[]},{"id":"c1","author":"ana","replies":[{"id":"c2","author":"bo","replies":[]},{"id":"c3","author":"zed","replies":[]}]}]
Explanation: c2 and c3 reply to c1; c4 has a deleted parent so it becomes top-level.

Example 2

Input: comments = []
Output: []

Constraints

  • 0 <= comments.length <= 10^4
  • ids are unique non-empty strings
  • The parent links contain no cycles
Hint 1

First create a node for every comment in a Map, then attach each node to its parent.

Hint 2

Sort each replies list once all nodes are attached.

Good practice for: Frontend Developer, Full Stack Developer, Mobile App Developer, Automation Test Engineer, Backend Developer

Run checks your code on 3 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.