Minimum Adjacent Swaps to Alternate Parity - Problem

You are given an array nums of distinct integers. In one operation, you can swap any two adjacent elements in the array.

An arrangement of the array is considered valid if the parity of adjacent elements alternates, meaning every pair of neighboring elements consists of one even and one odd number.

Return the minimum number of adjacent swaps required to transform nums into any valid arrangement. If it is impossible to rearrange nums such that no two adjacent elements have the same parity, return -1.

Input & Output

Example 1 — Basic Valid Case
$ Input: nums = [3,1,4,2]
Output: 3
💡 Note: We have 2 evens (4,2) and 2 odds (3,1). We can arrange as [1,4,3,2] (odd-even-odd-even) with 3 adjacent swaps: 3↔1, 1↔4, 4↔3.
Example 2 — Already Alternating
$ Input: nums = [1,2,3,4]
Output: 0
💡 Note: Array already alternates: odd-even-odd-even. No swaps needed.
Example 3 — Impossible Case
$ Input: nums = [1,3,5,7]
Output: -1
💡 Note: All numbers are odd. Cannot create alternating parity pattern.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000
  • All integers in nums are distinct

Visualization

Tap to expand
Minimum Adjacent Swaps to Alternate ParityInput Array3142oddoddevenevenProblem: Adjacent elements have same parity!Target: Alternating Pattern1432oddevenoddevenResult: 3 adjacent swaps needed
Asked in
Google 25 Microsoft 18 Amazon 15
23.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen