Save 25%Black Friday: 25% off all plans — use code BLACKFRIDAY2026 at checkout. Ends Friday, Dec 4.Claim the deal

(This question is a variation of the LeetCode question 905. Sort Array By Parity. If you haven't completed that question yet, it is recommended to solve it first.)

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. If the array is already in the required state, return 0.

Note: The relative order of even numbers or odd numbers does not matter, but all evens must be placed before all odds.

Constraints:

  • 1 ≤ nums.length ≤ 10510^5
  • −109-10^9 ≤ nums[i] ≤ 10910^9

Example 1:

Input: nums = [3, 2, 4, 1, 5, 6] Output: 1 Explanation: One swap is sufficient to move all even numbers before odd numbers: Swapping 3 and 2.

Example 2:

Input: nums = [2, 4, 6, 1, 3, 5] Output: 0

Example 3:

Input: nums = [1, 3, 5, 2, 4, 6] Output: 3


Accepted
1.7k/2.3k
Acceptance Rate75.0%
Test Cases
Input
nums =
Output
Expected