KatInterview

Interleave Two Linked Lists by Position Parity

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked listspointer manipulationreordering

Last updated

Tests pointer manipulation and node reordering by splitting a singly linked list (given as an array) into odd- and even-indexed sublists and merging them in a specific interleaved pattern.

Interleave Two Linked Lists by Position Parity

You are given a singly linked list represented as a list of integer values nodes, where nodes[0] is the head.

Your task is to reorder the list as follows:

  1. Split the list into two sublists:
    • Odd-indexed nodes: nodes at positions 1, 3, 5, … (0-indexed)
    • Even-indexed nodes: nodes at positions 0, 2, 4, … (0-indexed)
  2. Reverse the odd-indexed sublist.
  3. Interleave the two sublists, starting with the first even-indexed node, then the first (now-reversed) odd-indexed node, then the second even-indexed node, then the second odd-indexed node, and so on.
  4. If one sublist is exhausted before the other, append the remaining nodes of the longer sublist to the end.

Return the reordered list as a plain Python list of integers.

Example walkthrough (not shown as a sample case):

For nodes = [10, 20, 30, 40, 50]:

  • Even-indexed (0-based): [10, 30, 50] (positions 0, 2, 4)
  • Odd-indexed (0-based): [20, 40] (positions 1, 3)
  • Reversed odd: [40, 20]
  • Interleaved: 10, 40, 30, 20, 50 → [10, 40, 30, 20, 50]

Constraints

  • 0 ≤ len(nodes) ≤ 2000
  • -10^6 ≤ nodes[i] ≤ 10^6
  • When len(nodes) == 0, return [].
  • When len(nodes) == 1, return the list unchanged.
  • Node values are not necessarily unique.

Examples

Example 1

Input: interleave_by_parity([10, 20, 30, 40, 50])

Output: [10, 40, 30, 20, 50]

Example 2

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

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

Example 3

Input: interleave_by_parity([7])

Output: [7]

Hints

Hint 1

Start by partitioning the input into two separate lists based on index parity (even vs. odd indices).

Hint 2

After reversing the odd-indexed sublist, use two pointers — one into each sublist — and alternate appending elements to the result.

Hint 3

Handle the tail carefully: once one pointer is exhausted, append all remaining elements from the other sublist in order.