Social feed~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-637bfs
A social app shows a comment thread. Each comment has at most two direct replies, a left one and a right one, and a count of reactions. The comment at the top is the post's first comment.
Your team lead wants a small chart: for each level of the thread, the average number of reactions on its comments, rounded down. Level 1 is the top comment, level 2 holds its replies, and so on.
Write average_reactions_per_level(values, left, right).
0 to n - 1, and comment 0 is the top. An empty thread has three empty lists.values[i] is the number of reactions on comment i. left[i] and right[i] are the numbers of its replies, or -1 where there is none.Input: values = [8, 3, 10, 1, 6, 14, 4, 7, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
Output: [8, 6, 7, 8]Comment 0 (8 reactions) has the replies 1 (3) and 2 (10). Comment 1 has 3 (1) and 4 (6). Comment 2 has only a right reply 5 (14).
Comment 4 has 6 (4) and 7 (7). Comment 5 has only a left reply 8 (13).
Keep a queue of the comments waiting. At the start of each round, the number of comments in the queue is exactly one level.
| Round | Queue at the start (reactions) | Comments in the level | Total | Average, rounded down | Queue at the end |
|---|---|---|---|---|---|
| 1 | 8 | 1 | 8 | 8 | 3, 10 |
| 2 | 3, 10 | 2 | 13 | 6 | 1, 6, 14 |
| 3 | 1, 6, 14 | 3 | 21 | 7 | 4, 7, 13 |
| 4 | 4, 7, 13 | 3 | 24 | 8 | empty |
Level 2 has the average 6.5, which is rounded down to 6.
Input: values = [7], left = [-1], right = [-1]
Output: [7]Input: values = [], left = [], right = []
Output: []An empty thread has no levels.
0 ≤ length of values = length of left = length of right ≤ 10^50 ≤ values[i] ≤ 10^6left and right is -1 or a comment number from 1 to n - 10A thread can be one chain of 100,000 replies, which has 100,000 levels. Finding each level by scanning every comment costs about n^2 steps on it.
A level can also hold over 30,000 comments of up to 10^6 reactions each, so its total can pass 3 x 10^10. That does not fit in a 32-bit integer. Add the totals in a 64-bit number.