KatInterview

Interleave Linked List Halves by Node Values

Linked ListsAuto-graded · 17 test cases
HardAuto-gradedLinked Listslinked listsarray manipulationtwo pointers

Last updated

Tests pointer-manipulation intuition by reordering a linked list (given as an array) into a specific interleaved pattern derived from splitting and reversing halves.

Interleave Linked List Halves

You are given a singly linked list represented as a plain Python list of integers nodes. The list has n nodes with values nodes[0], nodes[1], ..., nodes[n-1].

Your task is to reorder the list in the following way:

  1. Split the list into two halves. If n is odd, the first half gets the extra node.
    • First half: indices 0 .. ceil(n/2) - 1
    • Second half: indices ceil(n/2) .. n-1
  2. Reverse the second half.
  3. Interleave the two halves: take one node from the first half, then one node from the (reversed) second half, alternating, until all nodes are used. Because the first half is longer or equal, any leftover node from the first half goes at the very end.

Return the reordered list of node values.

Details

  • The operation is performed purely on the values; treat nodes as a linked list whose next pointers you are rearranging, but represent your answer as a Python list.
  • The interleaving picks alternately: first[0], second_rev[0], first[1], second_rev[1], …
  • When n is odd the first half has one more element than the second; that extra element is appended last.

Constraints

  • 0 ≤ n ≤ 2000
  • -10^6 ≤ nodes[i] ≤ 10^6
  • If n == 0 return [].
  • If n == 1 return the single-element list unchanged.
  • Values are not necessarily distinct.

Examples

Example 1

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

Output: [1, 4, 2, 3]

Example 2

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

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

Example 3

Input: reorder_linked_list_halves([7])

Output: [7]

Hints

Hint 1

Find the midpoint using the classic slow/fast pointer technique (simulate it on the array with two indices).

Hint 2

Reverse only the second half in-place or into a new list, then merge the two halves with a two-pointer interleave.

Hint 3

Be careful about which half gets the extra node when n is odd — the first half does, and that lone extra node lands at the very end of the result.