Monitoring~25 min2s · 256 MBtarget O(n) time, O(h) spaceclassic twin: lc-99tree-recursion
A monitoring system keeps the ids of its alerts in a search tree. A faulty job has swapped the ids of exactly two nodes, so the tree is no longer in order, but its shape is untouched.
The tree can hold 100,000 alerts. Your team lead wants the two ids put back, without changing any link.
Write recover_values(values, left, right).
0 to n - 1, and alert 0 is the top of the tree. There are at least two alerts.values[i] is the id of alert i. left[i] and right[i] are the alerts on its left and right, or -1 where there is none. The ids are distinct.Input: values = [8, 7, 10, 1, 6, 14, 4, 3, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
Output: [8, 3, 10, 1, 6, 14, 4, 7, 13]The ids 3 and 7 were swapped. A walk in order gives [1, 7, 4, 6, 3, 8, 10, 13, 14] and it should be increasing. It drops twice, from 7 to 4 and from 6 to 3. The first drop names the earlier alert, and the last drop names the later one.
| Taken (node, id) | Id before it | Drop? | first (id) |
second (id) |
|---|---|---|---|---|
| 3 (1) | none | no | none | none |
| 1 (7) | 1 | no | none | none |
| 6 (4) | 7 | yes | 7 | 4 |
| 4 (6) | 4 | no | 7 | 4 |
| 7 (3) | 6 | yes | 7 | 3 |
| 0 (8) | 3 | no | 7 | 3 |
| 2 (10) | 8 | no | 7 | 3 |
| 8 (13) | 10 | no | 7 | 3 |
| 5 (14) | 13 | no | 7 | 3 |
The alerts holding 7 and 3 are swapped back, which gives [8, 3, 10, 1, 6, 14, 4, 7, 13].
Input: values = [2, 1], left = [1, -1], right = [-1, -1]
Output: [2, 1]Input: values = [7, 3, 10, 1, 6, 14, 4, 8, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
Output: [8, 3, 10, 1, 6, 14, 4, 7, 13]2 ≤ length of values = length of left = length of right ≤ 10^51 ≤ values[i] ≤ 10^9, and the ids are distinctleft and right is -1 or an alert number from 1 to n - 10, and its ids are a search tree with exactly two ids swappedTrying every pair of alerts, swapping, and checking the order costs n for each of about n^2 / 2 pairs. For 100,000 alerts that is far beyond any limit.
A walk in order is a single pass of n steps. Where it drops, the two swapped ids reveal themselves.