Skip to the code
cf.
+25 XP

#358 Nest a Flat List of Comments

medium

A comments API returns a flat list of rows like { "id": 4, "parentId": 1 }. A row with parentId: null is a top-level comment. Rows can come in any order: a reply may appear before the comment it answers.

Write nestComments(rows) that returns the top-level comments as an array of { "id": ..., "replies": [...] } objects, where replies holds that comment's direct replies in the same shape, all the way down. Keep top-level comments and each comment's replies in the order their rows appear in rows. Every parentId that isn't null refers to a row in the list, and there are no cycles.

Example 1

Input: rows = [{"id":1,"parentId":null},{"id":2,"parentId":1},{"id":3,"parentId":null},{"id":4,"parentId":1}]
Output: [{"id":1,"replies":[{"id":2,"replies":[]},{"id":4,"replies":[]}]},{"id":3,"replies":[]}]

2 and 4 reply to 1, in that order; 3 is a second top-level comment.

Example 2

Input: rows = [{"id":9,"parentId":5},{"id":5,"parentId":null}]
Output: [{"id":5,"replies":[{"id":9,"replies":[]}]}]

The reply comes first in the list, but it still ends up under 5.

Constraints

  • 0 <= rows.length <= 10^4
  • Ids are unique.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).