Problem 285352 · medium · Phase 02 Linear Data Structures

Match Parity to Position

arrays · stable partition · slice assignment

Given a list of integers nums of even length containing exactly as many even numbers as odd numbers, return a new list of the same length in which every even index holds an even number and every odd index holds an odd number. The even numbers must keep their relative order, and so must the odd numbers.

Examples

Input:  nums = [3, 4, 1, 2]
Output: [4, 3, 2, 1]
Explanation: evens 4, 2 go to indices 0 and 2; odds 3, 1 go to indices 1 and 3.

Input:  nums = [1, 2]
Output: [2, 1]

Constraints

  • 0 <= len(nums) <= 10**5, length even, equal counts of even and odd values
  • Return a new list.
  • Target: O(n) time; do not sort.

Goals

  • Split values by parity while keeping order
  • Place two groups into alternating positions
  • Use extended slices to write every other index
Starting Python…