← Questions

Minimum swaps to put evens before odds

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests arrays, two pointers and greedy.

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.

Clarifying questions

  • How should negative values be classified (-3 is odd, -4 is even)?
  • Is an empty array or an all-even or all-odd array answered with 0?
  • Must the function also return the rearranged array, or only the count?
  • Is a swap of two values with the same parity ever useful?

What a strong answer covers

  • Counts the evens e; the first e slots must hold evens, so the answer is the number of odd values among the first e slots.
  • Explains why that is optimal: each misplaced odd in the even zone pairs with one misplaced even in the odd zone, one swap fixes one pair, and no swap can fix two.
  • Two passes, O(n) time and O(1) space; parity with x % 2 (or x & 1) so negatives work.
  • Tests the examples, an empty array, and an array with all odds first.

Follow-ups

  • Only adjacent swaps are allowed.
  • Keep the relative order inside each group and count the moves.
  • Extend to three classes, such as values mod 3.

Where it's asked

What it tests

arrays · two pointers · greedy

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