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 Parity INPUT nums = [3, 1, 4, 2] 3 odd 1 odd 4 even 2 even Parity Analysis: Odd: 2 Even: 2 |odd - even| <= 1 Valid arrangement possible! Target: O-E-O-E or E-O-E-O ALGORITHM STEPS 1 Try Pattern 1: O-E-O-E [3,1,4,2] count swaps needed 2 Try Pattern 2: E-O-E-O [3,1,4,2] count swaps needed Greedy Swap Process: [3,1,4,2] pos 0: need odd, have 3 OK [3,1,4,2] pos 1: need even [3,4,1,2] swap 1-2 (1 swap) [3,4,1,2] pos 2: need odd OK [3,4,1,2] pos 3: need even OK 3 Compare Both Patterns Pattern1: 3 swaps, Pattern2: 1 swap 4 Return Minimum min(3, 1) = 1... wait check! FINAL RESULT Valid Arrangement: 3 4 1 2 O - E - O - E pattern Swap Trace: [3,1,4,2] --> swap(1,4) [3,4,1,2] --> swap(1,4) [3,4,1,2] Done! Output: 3 Minimum swaps needed to alternate parity Key Insight: For valid alternating parity, |count(odd) - count(even)| must be <= 1. If counts differ by more, return -1. Use greedy approach: for each position, find nearest element with required parity and swap it into place. Try both O-E-O-E and E-O-E-O patterns, return minimum swaps. TutorialsPoint - Minimum Adjacent Swaps to Alternate Parity | Greedy Pattern Matching
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