Minimum swaps to put evens before odds
I was asked this
No reports yet. Sign in to say where you were asked it.
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 (
-3is odd,-4is 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 firsteslots must hold evens, so the answer is the number of odd values among the firsteslots. - 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 andO(1)space; parity withx % 2(orx & 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
