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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code