Ctrl K

Parity in Its Place

Easy
You are given an array values of even length in which exactly half of the numbers are even. Arrange them so that even positions (0, 2, 4, …) hold even numbers and odd positions hold odd numbers. Follow this rule. Walk over the even positions from left to right. Whenever an even position holds an odd number, swap it with the number at the leftmost odd position that currently holds an even number. Return the array after all the swaps. Try to do it in place and in a single pass.
Example 1
values=[5, 8, 3, 2, 6, 7] → [8, 5, 2, 3, 6, 7]

Even position 0 holds the odd 5, so it swaps with the first misplaced value at an odd position, the 8 at position 1: [8, 5, 3, 2, 6, 7]. Position 2 holds 3, and the next misplaced odd position is 3, holding 2: [8, 5, 2, 3, 6, 7]. Position 4 is already fine.

Example 2
values=[1, 4] → [4, 1]

A single swap gives [4, 1].

Constraints
  • 2 ≤ len(values) ≤ 2 · 10⁵
  • len(values) is even
  • exactly half of the numbers are even
  • 0 ≤ values[i] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMerge Into the Spare Tail EasyValues in Both Lists EasyShared Values With Repeats EasyCake Slices for Guests EasyEvens to the Left Easy
loading Python…
Input
values=[5, 8, 3, 2, 6, 7]
Expected
[8, 5, 2, 3, 6, 7]

Run checks the first 3 tests in your browser. Submit checks all 76 tests on the server, hidden ones included.