Social feed~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-863tree-recursion
A feed app shows comments in a reply tree. Each comment has up to two direct replies, and comment 0 is the first one.
When a reader opens a comment, the app highlights every comment that is exactly k links away. Those can be replies below it, the comment it answers, and the other replies under that comment.
The tree can hold 100,000 comments and can be a chain. Your team lead wants one pass for each opened comment.
Write comments_k_away(left, right, target, k).
0 to n - 1, and comment 0 is the first. left[i] and right[i] are the replies to comment i, or -1 where there is none.target is the comment that was opened. k is a distance, from 0 to n.k links from target, in increasing order. The list is empty when there are none.Input: left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], target = 1, k = 2
Output: [2, 6, 7]From comment 1, the comments 1 link away are 0, 3 and 4. The comments 2 links away are 2, 6 and 7.
| Round | Ring: the comments at this distance | Comments seen so far |
|---|---|---|
| 0 | [1] |
1 |
| 1 | [0, 3, 4] |
4 |
| 2 | [2, 6, 7] |
7 |
The walk up reaches comment 0, and from there it reaches comment 2 on the other side.
Input: left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], target = 0, k = 0
Output: [0]Distance 0 is the comment itself.
Input: left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], target = 8, k = 3
Output: [0]The path goes up from comment 8 through comments 5 and 2 to comment 0.
1 ≤ length of left = length of right ≤ 10^5left and right is -1 or a comment number from 1 to n - 100 ≤ target ≤ n - 1 and 0 ≤ k ≤ nThe tree can be a chain of 100,000 comments, so a path can have 99,999 links. Working out the distance from the target to each comment by climbing from the top costs a climb for every comment. On a chain that is about n^2 / 2 steps, or 5 x 10^9.
Store each comment's parent once, then grow a ring outwards from the target. Each comment joins the ring at most once, so the whole work is n steps.