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.
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.
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.
0 <= rows.length <= 10^4Run 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).
I'm here to help with #358 Nest a Flat List of Comments. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.