KatInterview

Partition Array Into Alternating Parity Groups

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarraystwo pointersin-place partitioning

Last updated

Tests in-place partitioning by rearranging an integer array so all even-indexed positions hold even numbers and all odd-indexed positions hold odd numbers, without allocating a new array.

Partition Array Into Alternating Parity Groups

You are given a list of integers that is guaranteed to contain exactly as many even numbers as odd numbers. Your task is to rearrange the list in-place so that:

  • Every even index (0, 2, 4, …) holds an even number.
  • Every odd index (1, 3, 5, …) holds an odd number.

Because multiple valid arrangements exist, the following tie-break rule defines a unique answer:

  1. Collect all even numbers from the original list, preserving their relative order.
  2. Collect all odd numbers from the original list, preserving their relative order.
  3. Interleave them: position 0 ← even[0], position 1 ← odd[0], position 2 ← even[1], position 3 ← odd[1], …

You must perform this rearrangement in-place (modify the input list directly) and also return it.

Constraints

  • 2 ≤ len(nums) ≤ 2000
  • len(nums) is always even.
  • The list always contains exactly len(nums) // 2 even numbers and len(nums) // 2 odd numbers.
  • -10^6 ≤ nums[i] ≤ 10^6
  • 0 is considered even.
  • Negative numbers retain their usual parity (e.g., -3 is odd, -4 is even).

Examples

Example 1

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

Output: [4, 1, 2, 3]

Example 2

Input: partition_alternating_parity([10, 7, 6, 3, 2, 5])

Output: [10, 7, 6, 3, 2, 5]

Example 3

Input: partition_alternating_parity([0, -3, -4, 9])

Output: [0, -3, -4, 9]

Hints

Hint 1

Try making two passes first: one to collect even-indexed values (the evens in order) and one to collect odd-indexed values (the odds in order), then write them back in-place.

Hint 2

You can use two write-pointers — one stepping by 2 starting at index 0 for even numbers, another stepping by 2 starting at index 1 for odd numbers — and a single read-pass over the original values.

Hint 3

To keep it truly in-place, save the original values with a temporary copy of the array before overwriting, or partition using index arithmetic rather than a new list.