Skip to the code
cf.
+25 XP

#745 Flatten a Comment Thread

medium

A discussion page renders nested comments with a virtualized list, which needs a flat list of rows. Each comment is { id, replies }, where replies is a list of comments in display order. Users can collapse a comment: it is still shown, but its replies (and everything under them) are hidden.

Write flattenThread(comments, collapsed) that returns the visible rows as [id, depth] pairs in display order: a comment appears before its replies, and top-level comments have depth 0. collapsed is a list of collapsed comment ids.

Example 1

Input: comments = [{"id":"c1","replies":[{"id":"c2","replies":[{"id":"c3","replies":[]}]},{"id":"c4","replies":[]}]},{"id":"c5","replies":[{"id":"c6","replies":[]}]}], collapsed = []
Output: [["c1",0],["c2",1],["c3",2],["c4",1],["c5",0],["c6",1]]

Every comment is shown, each before its replies.

Example 2

Input: comments = [{"id":"c1","replies":[{"id":"c2","replies":[{"id":"c3","replies":[]}]},{"id":"c4","replies":[]}]},{"id":"c5","replies":[{"id":"c6","replies":[]}]}], collapsed = ["c2","c5"]
Output: [["c1",0],["c2",1],["c4",1],["c5",0]]

c2 and c5 are collapsed, so c3 and c6 are hidden.

Constraints

  • At most 10^4 comments in total, nested up to 1000 levels.
  • ids are unique strings.
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).