Minimum swaps to put evens before odds
I was asked this
No reports yet. Sign in to say where you were asked it.
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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
