Search~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-430linked-lists
A search results page shows results as a two-way chain. A result can have a child chain of sub-results hanging from it, and a sub-result can have its own children, to any depth. An Expand all button must turn the whole structure into one flat two-way chain.
The children of a result must appear right after it, and before the result that followed it. The page has up to 100,000 results.
Write flatten_chain(head, after, before, inside).
n - 1.after[i] is the slot after slot i in its chain, or -1 for the last.before[i] is the slot before it, or -1 for the first.inside[i] is the first slot of the child chain of slot i, or -1 for none.head is the first slot of the top chain, or -1 when there are no results.inside to -1, and keep every before correct.2 × n numbers. For each slot in the flat order from head, write the slot, then its before after flattening.Input: head = 0, after = [1, 2, -1, 4, -1, 6, -1], before = [-1, 0, 1, -1, 3, -1, 5], inside = [-1, 3, -1, -1, 5, -1, -1]
Output: [0, -1, 1, 0, 3, 1, 4, 3, 5, 4, 6, 5, 2, 6]The top chain is 0, 1, 2. Slot 1 has the child chain 3, 4, and slot 4 has the child chain 5, 6. The flat order is 0, 1, 3, 4, 5, 6, 2.
| Step | cur | Child chain | What happens | Main chain from head |
|---|---|---|---|---|
| [1] | 0 | start on the head | 0 → 1 → 2 | |
| [4] | 0 | none | no child, move on | |
| [2], [3] | 1 | 3 → 4 | splice the child chain in; its last slot 4 now points at 2 | 0 → 1 → 3 → 4 → 2 |
| [4] | 3 | none | no child, move on | |
| [2], [3] | 4 | 5 → 6 | splice the child chain in; its last slot 6 now points at 2 | 0 → 1 → 3 → 4 → 5 → 6 → 2 |
| [4] | 5 | none | no child, move on | |
| [4] | 6 | none | no child, move on | |
| [4] | 2 | none | no child, move on | |
| [5] | read back | [0, -1, 1, 0, 3, 1, 4, 3, 5, 4, 6, 5, 2, 6] |
Input: head = 0, after = [-1], before = [-1], inside = [-1]
Output: [0, -1]One result with no children.
Input: head = -1, after = [], before = [], inside = []
Output: []0 ≤ n ≤ 10^5, and after, before and inside have the same length.head is -1, or a slot from 0 to n - 1.n - 1. The tables describe a valid structure: every slot belongs to exactly one chain, and before matches after.Starting again from the head after every splice costs a walk past all the nodes that are already flat. With 5 × 10^4 results that each have a child, that is about 2.5 × 10^9 steps.
Continuing from the node you spliced, and never going back, touches each node a constant number of times.