Chat app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-24linked-lists
A chat app syncs a thread from a phone. A bug in the sync step saved every two neighbouring messages in the wrong order. Messages 1 and 2 are swapped, then messages 3 and 4, and so on. A last message with no partner is fine.
The thread is a chain of nodes, and each node carries attachments. The repair must move the nodes themselves, and not copy ids between them. A thread can hold up to 100,000 messages.
Write swap_every_two(head).
head is the first node of the thread, or null when the thread is empty. Each node's val is a message id.The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [101, 102, 103, 104]
Output: [102, 101, 104, 103]| Step | prev | first | second | Pointer changes | The chain now |
|---|---|---|---|---|---|
| [1] | placeholder | placeholder → 101 → 102 → 103 → 104 | |||
| [2] round 1 | placeholder | 101 | 102 | 101 → 103, 102 → 101, placeholder → 102 | placeholder → 102 → 101 → 103 → 104 |
| [4] | 101 | prev moves to 101 | |||
| [2] round 2 | 101 | 103 | 104 | 103 → null, 104 → 103, 101 → 104 | placeholder → 102 → 101 → 104 → 103 |
| [4] | 103 | prev moves to 103; nothing follows it, so the loop ends | |||
| [5] | return 102 → 101 → 104 → 103 |
Each round makes three pointer changes, and their order matters.
Input: head = [5, 6, 7]
Output: [6, 5, 7]Three messages: the pair is swapped, and the last message has no partner.
Input: head = [9]
Output: [9]One message has no partner, so the thread is unchanged.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^9One walk down the chain is 10^5 hops, far inside the time limit. A plan that walks from the head to every pair makes about n^2 / 4 hops: 2.5 × 10^9 at this size, which is too slow.
A note on the tests: they read only the values, so they cannot tell a node swap from a value swap. Moving the nodes is the rule all the same, because the nodes carry attachments.
The statement also asks you to move the nodes, not to copy ids between them. So copying the thread into an array does not help. Visit each pair once and change three pointers: that is O(n) time and O(1) extra memory.