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.
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.
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.
10^4 comments in total, nested up to 1000 levels.ids are unique strings.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).
I'm here to help with #745 Flatten a Comment Thread. 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.