AlgoInsight

DSA problem

Reorder List

MediumLinked ListPattern: Linked Listtop600AmazonMicrosoftFacebookBloombergApple

You are given the head of a singly linked list. The list can be conceptually represented as L0 -> L1 -> ... -> Ln-1 -> Ln. Reorder it into the interleaved form L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 -> ..., where you alternately take a node from the front and a node from the back. You may not modify the values stored in the nodes; only the node pointers themselves may change.

A brute-force solution would store the nodes in an array for O(1) random access by index and then re-link them, but that requires O(n) extra space. The optimal solution achieves the reordering in O(1) extra space using only pointer manipulation.

The reordering combines three classic linked-list techniques. First, find the middle node using the slow/fast pointer method. Second, reverse the second half of the list in place. Third, merge the first half and the reversed second half by alternating nodes from each.

The intuition is that after splitting and reversing, the second half traversed forward gives exactly the back-to-front order we want (Ln, Ln-1, ...). Merging it node-by-node with the first half produces the alternating pattern directly. Each of the three phases is linear and uses constant space, so the overall algorithm is O(n) time and O(1) space.

Examples

Example 1
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Explanation: Taking from the front then the back: 1, then 4, then 2, then 3 gives [1,4,2,3].
Example 2
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
Explanation: Alternating front and back: 1, 5, 2, 4, and finally the middle node 3 yields [1,5,2,4,3].
Example 3
Input: head = [1,2]
Output: [1,2]
Explanation: With only two nodes, the front node 1 followed by the back node 2 is already the reordered form.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listtwo-pointersin-placerecursion

Browse all DSA problems