← Questions

Minimum swaps to put evens before odds

0
MicrosoftCoding

Given an integer array nums of length n, you want every even value to come before every odd value. In one move you may swap the values at any two distinct indices.

Return the minimum number of swaps needed. If the array already has all evens before all odds, return 0. The order of values inside the even block and inside the odd block does not matter.

def min_swaps_evens_first(nums: list[int]) -> int: ...

Constraints

  • 0 <= n <= 10^5
  • -10^9 <= nums[i] <= 10^9 (zero is even; negative values follow normal parity)

Example 1

nums = [5, 2, 8, 1, 6]
output: 1

There are three evens, so the first three slots must hold evens. Only 5 is out of place there; swapping it with the 6 at the end gives [6, 2, 8, 1, 5].

Example 2

nums = [1, 3, 2, 4]
output: 2

Both odds sit in the two slots reserved for evens, and each swap can fix only one of them.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding