Skip to main content

Minimum Swaps to Sort Array By Parity

easy
Software engineer

You are given an integer array nums of length n. Rearrange nums so that all even numbers appear before all odd numbers.

You may swap values at any two distinct indices. Return the minimum number of swaps needed to achieve this arrangement.

Note: The relative order of even numbers or odd numbers does not matter, as long as all even integers precede all odd integers.

(This question is a variation of Sort Array By Parity, focusing on the swap count rather than the resulting array.)

Example 1

Input

nums = [3, 2, 4, 1, 5, 6]

Output

1

Explanation

There are three even numbers (2, 4, 6). In a parity-sorted array, these must occupy the first three indices (0, 1, and 2). 
- Index 0 currently has an odd number (3).
- Index 1 and 2 already have even numbers (2, 4).
- Looking at the suffix (indices 3-5), index 5 contains an even number (6) that belongs in the front.
- By swapping nums[0] (3) with nums[5] (6), the array becomes [6, 2, 4, 1, 5, 3]. Now all evens are at the front. Total swaps: 1.

Example 2

Input

nums = [2, 4, 6, 1, 3, 5]

Output

0

Explanation

All even numbers are already at the beginning of the array.

Example 3

Input

nums = [1, 3, 5, 2, 4, 6]

Output

3

Explanation

All three even numbers are in the 'odd' section. Three swaps are needed to bring them to the front.

Constraints

  • 1 <= nums.length <= 10⁵
  • -10⁹ <= nums[i] <= 10⁹

Onsite

ArrayGreedySimulationTwo Pointers
Language
Code editor loads in the browser.

Output

Input

[3,2,4,1,5,6]

Expected

1

Your output

Run to see your output.