KatInterview

Interleave Two Halves of a Linked List (Array Form)

Linked ListsAuto-graded · 19 test cases
MediumAuto-gradedLinked Listslinked listtwo pointersarray manipulation

Last updated

Tests pointer-manipulation thinking by reordering a node list so that the first half and reversed second half are interleaved, all represented as arrays of values.

Interleave Two Halves of a Linked List

You are given a singly linked list represented as a plain Python list of integers nodes, where nodes[i] is the value of the i-th node in order.

Your task is to reorder the list in-place (return a new list) so that the final order follows the pattern:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

In other words, repeatedly take one node from the front of the original list, then one node from the back, until all nodes are consumed.

  • If nodes is empty, return [].
  • If nodes has one element, return it unchanged.
  • For an odd number of nodes, the middle node appears in the correct interleaved position (front pointer reaches it last before the two pointers meet).

No sorting is performed; only the positions of the existing values change.

Constraints

  • 0 ≤ len(nodes) ≤ 2000
  • -10^6 ≤ nodes[i] ≤ 10^6
  • Values are not necessarily distinct.
  • You must return a new list; do not modify the input.

Examples

Example 1

Input: interleave_halves([1, 2, 3, 4, 5])

Output: [1, 5, 2, 4, 3]

Example 2

Input: interleave_halves([1, 2, 3, 4])

Output: [1, 4, 2, 3]

Example 3

Input: interleave_halves([42])

Output: [42]

Hints

Hint 1

Use two pointers (left starting at 0, right starting at len-1) and advance them toward each other, appending alternately to a result list.

Hint 2

Be careful about the termination condition: stop when left >= right to avoid adding the middle element twice in the odd-length case.

Hint 3

Trace through a small example like [1,2,3,4,5]: take 1 (front), 5 (back), 2 (front), 4 (back), 3 (middle) → [1,5,2,4,3].