Minimum Adjacent Swaps to Alternate Parity - Problem

Imagine you have an array of distinct integers where you need to arrange them in a specific pattern - every adjacent pair must have alternating parity (one even, one odd).

You can perform adjacent swaps - swapping any two neighboring elements in a single operation. Your goal is to find the minimum number of swaps needed to create a valid alternating pattern.

For example, in array [1, 2, 3, 4], a valid arrangement could be [1, 2, 3, 4] (odd-even-odd-even) or [2, 1, 4, 3] (even-odd-even-odd). Both patterns are acceptable!

Return: The minimum number of adjacent swaps needed, or -1 if it's impossible to create any valid alternating arrangement.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 2, 3, 4]
โ€บ Output: 0
๐Ÿ’ก Note: The array is already alternating: odd-even-odd-even. No swaps needed.
example_2.py โ€” Requires Swaps
$ Input: nums = [1, 3, 2, 4]
โ€บ Output: 1
๐Ÿ’ก Note: We need to swap elements at positions 1 and 2 to get [1, 2, 3, 4] which alternates odd-even-odd-even.
example_3.py โ€” Impossible Case
$ Input: nums = [1, 3, 5, 7]
โ€บ Output: -1
๐Ÿ’ก Note: All numbers are odd, so we cannot create an alternating pattern of odd-even. Return -1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 103
  • 1 โ‰ค nums[i] โ‰ค 105
  • All elements in nums are distinct
  • You can only swap adjacent elements

Visualization

Tap to expand
Dance Line Alternating PatternOriginal Line:TTSS[Tall, Tall, Short, Short]Pattern 1: T-S-T-STSTSโœ“ 1 swap neededPattern 2: S-T-S-TSTSTโœ“ 3 swaps neededSwap AnimationOriginal: Tโ‚-Tโ‚‚-Sโ‚-Sโ‚‚Step 1: Tโ‚-Sโ‚-Tโ‚‚-Sโ‚‚โœ“ Perfect alternating!1 adjacent swap๐ŸŽฏ Key InsightOnly 2 possible alternating patterns!Try both and pick the one with fewer swapsTime Complexity: O(nยฒ) for counting swaps in each pattern
Understanding the Visualization
1
Count Dancers
First, count how many tall vs short dancers we have
2
Check Possibility
For alternating pattern, counts can differ by at most 1
3
Try Both Patterns
Test starting with tall-short vs short-tall pattern
4
Calculate Swaps
For each pattern, count adjacent swaps needed
5
Choose Minimum
Return the pattern requiring fewer swaps
Key Takeaway
๐ŸŽฏ Key Insight: Since there are only two possible alternating patterns (odd-even or even-odd starting), we can try both and choose the one requiring minimum swaps, making this much more efficient than brute force!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
28.5K Views
Medium Frequency
~18 min Avg. Time
890 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