KatInterview

Weave Two Halves of a Linked List

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

Last updated

Tests pointer manipulation intuition by reordering a singly linked list represented as an array, interleaving nodes from the front and back halves.

Weave Two Halves of a Linked List

You are given a singly linked list represented as an array nodes, where nodes[i] is the value of the i-th node (0-indexed, from head to tail).

Your task is to reorder the list in-place using the following rule:

Interleave nodes taken alternately from the front and the back of the original list, always picking from the front first.

Concretely, if the original list has nodes at indices 0, 1, 2, ..., n-1, the reordered list should be:

index 0, index n-1, index 1, index n-2, index 2, index n-3, ...

Return the reordered list as a new array.

Details:

  • The "front pointer" starts at index 0 and moves right.
  • The "back pointer" starts at index n-1 and moves left.
  • At each step, append the front element, then the back element (if the two pointers haven't crossed or met).
  • Stop adding elements once every original node has been placed exactly once.
  • If nodes is empty, return an empty list.

Constraints

  • 0 <= len(nodes) <= 2000
  • -10^6 <= nodes[i] <= 10^6
  • Each node value is an integer.

Examples

Example 1

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

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

Example 2

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

Output: [1, 4, 2, 3]

Example 3

Input: weave_halves([])

Output: []

Hints

Hint 1

Use two pointers, one starting at the beginning and one at the end, and advance them toward each other.

Hint 2

Be careful about the stopping condition: once the front pointer index is >= the back pointer index, you should stop appending the back element to avoid duplicating the middle node of an odd-length list.

Hint 3

Simulate the process with a small odd-length example (e.g., [1,2,3,4,5]) and a small even-length example (e.g., [1,2,3,4]) to verify your logic handles the middle node correctly.