Chat app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-199bfs
A chat app draws its company directory as an org chart. Each person has at most two direct reports, a left one and a right one. The chart is drawn row by row, with the head of the company at the top, and the left report to the left of the right one.
Your team lead wants a compact view for a narrow phone screen: the people you would see if you looked at the chart from its right edge. On each row, only the person furthest to the right is visible.
Write right_edge_people(values, left, right).
0 to n - 1, and person 0 is the head. An empty chart has three empty lists.values[i] is the employee id of person i. left[i] and right[i] are the numbers of the direct reports of person i, 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, 10, 14, 13]Person 0 (id 8) has the reports 1 (id 3) and 2 (id 10). Person 1 has 3 (1) and 4 (6). Person 2 has only a right report 5 (14).
Person 4 has 6 (4) and 7 (7). Person 5 has only a left report 8 (13). The id 13 is on the left of person 5, but nobody is to its right on that row.
| Round | Queue at the start (ids) | People in the row | The last in the row | Queue at the end |
|---|---|---|---|---|
| 1 | 8 | 1 | 8 | 3, 10 |
| 2 | 3, 10 | 2 | 10 | 1, 6, 14 |
| 3 | 1, 6, 14 | 3 | 14 | 4, 7, 13 |
| 4 | 4, 7, 13 | 3 | 13 | empty |
Input: values = [1, 2, 3], left = [1, 2, -1], right = [-1, -1, -1]
Output: [1, 2, 3]A chain of left reports. Nobody has a right report, but each row has one person, who is visible.
Input: values = [], left = [], right = []
Output: []0 ≤ length of values = length of left = length of right ≤ 10^50 ≤ values[i] ≤ 10^6left and right is -1 or a person number from 1 to n - 10A chart can be one chain of 100,000 people, which has 100,000 rows. Scanning every person for every row costs about n^2 steps on it.
Build each row from the row above, and look at every person once.