KatInterview

Interleave Two Linked Lists from Their Midpoints

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked liststwo pointersarray manipulation

Last updated

Tests pointer-manipulation reasoning by reordering a singly linked list (given as an array) so nodes alternate between the first and second halves, starting from their respective midpoints.

Interleave Two Linked Lists from Their Midpoints

You are given a singly linked list represented as a plain Python list nodes, where nodes[i] is the value of the i-th node (0-indexed, head at index 0).

Your task is to reorder the list in-place (return the reordered values as a new list) according to the following rule:

  1. Split the list into two halves:

    • First half: indices 0 … m-1
    • Second half: indices m … n-1

    where m = ceil(n / 2) and n = len(nodes).
    (If the list has an odd number of nodes, the first half gets the extra node.)

  2. Reverse the second half.

  3. Interleave the two halves by alternating one node from the first half and one node from the (reversed) second half:

    first[0], second_rev[0], first[1], second_rev[1], …
    

    Because the first half is at least as long as the second half, if the first half has any leftover nodes after the second half is exhausted, append them at the end.

Return the reordered list of values.

Example walkthrough

For nodes = [1, 2, 3, 4, 5]:

  • First half: [1, 2, 3], second half: [4, 5]
  • Reversed second half: [5, 4]
  • Interleaved: [1, 5, 2, 4, 3]

Constraints

  • 0 ≤ len(nodes) ≤ 2000
  • -10^6 ≤ nodes[i] ≤ 10^6
  • If len(nodes) == 0 or len(nodes) == 1, return the list unchanged.
  • Values may contain duplicates.

Examples

Example 1

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

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

Example 2

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

Output: [1, 4, 2, 3]

Example 3

Input: interleave_from_midpoint([7])

Output: [7]

Hints

Hint 1

Find the midpoint using integer ceiling division: m = (n + 1) // 2.

Hint 2

Reverse the second half slice in place (or use Python slicing [::-1]) before interleaving.

Hint 3

Use two pointers—one walking the first half, one walking the reversed second half—and zip them together, then append any remainder from the first half.