All questions
MediumArrays · Sliding Window
Minimum Swaps to Group Evens
Written by a community member · · 1 attempt · 0% pass
0
Given a list of integers, determine the minimum number of adjacent swaps needed to group all even numbers together in one contiguous block.
Return the minimum number of adjacent swaps required.
Examples:
-
Input: nums = [3, 2, 4, 1, 6]
Output: 1
Explanation: The even numbers are at positions 1, 2, and 4. One adjacent swap is enough to make them consecutive. -
Input: nums = [1, 2, 3, 4, 5, 6]
Output: 2
Explanation: The even numbers can be grouped into a contiguous block with two adjacent swaps.
Constraints:
- 1 <= len(nums) <= 10^5
- -10^9 <= nums[i] <= 10^9
- The input list always contains at least one even number.
Your solution should run in O(n) time.