Social feed~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-143linked-lists · two-pointers
A social app has a throwback view. It shows a person's posts from both ends of their history in turn. The oldest post comes first, then the newest, then the second oldest, then the second newest, and so on.
The app keeps the posts as a chain of nodes, from the oldest to the newest, and a chain can hold up to 100,000 posts. The view must reuse the same nodes and must not copy the history.
Write reorder_thread(head).
head is the first node of the chain, the oldest post, or null when there are no posts. Each node's val is a post id.p1, p2, ..., pn the new order is p1, pn, p2, pn-1, p3, ....The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [10, 20, 30, 40, 50]
Output: [10, 50, 20, 40, 30]| Step | What happens | The chain now |
|---|---|---|
| [1] Find the last node of the first half | slow stops on 30 | 10 → 20 → 30 → 40 → 50 |
| [2] Cut after slow | 30 now points at null | first half 10 → 20 → 30, second half 40 → 50 |
| [3] Reverse the second half | 50 now leads, and 40 follows it | second half 50 → 40 |
| [4] Weave, round 1 | 10 takes 50, and 50 takes 20 | 10 → 50 → 20 → 30, with 40 waiting |
| [4] Weave, round 2 | 20 takes 40, and 40 takes 30 | 10 → 50 → 20 → 40 → 30 |
With an odd number of posts the middle post, 30, ends up last, and it is already in place.
Input: head = [10, 20, 30, 40]
Output: [10, 40, 20, 30]With an even number of posts both halves have two nodes, and the weave ends exactly when the second half is used up.
Input: head = [8]
Output: [8]One post is already in order.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^9Taking the last node by walking to it costs a walk, and you would do it once for every pair of posts. That is about n^2 / 4 hops: 2.5 × 10^9 at this size, which is too slow.
Copying the nodes into an array makes the order easy to build, but it costs O(n) extra memory, and the view must reuse the same nodes in place. So find the middle, reverse the second half, and weave the halves together. Each step is one linear walk.
A note on the tests: they read the values of your answer, and the judge does not measure extra memory. So a version that copies the nodes into an array and relinks them also passes. The in-place weave is the point of the problem.