#3587
Minimum Adjacent Swaps to Alternate Parity
MediumArrayGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Count the even and odd numbers. If their counts differ by more than one, return -1. Otherwise, compute the minimum swaps needed for two valid patterns: starting with even or odd.
⚙️
Algorithm
3 steps- 1Step 1: Count even and odd numbers in nums.
- 2Step 2: If abs(evenCnt - oddCnt) > 1, return -1.
- 3Step 3: Calculate swaps needed for both patterns (even-odd and odd-even) and return the minimum.
solution.py14 lines
1def min_swaps_optimal(nums):
2 evens = [x for x in nums if x % 2 == 0]
3 odds = [x for x in nums if x % 2 != 0]
4 if abs(len(evens) - len(odds)) > 1:
5 return -1
6 return min(count_swaps(nums, evens, odds, start=0), count_swaps(nums, odds, evens, start=1))
7
8def count_swaps(nums, first, second, start):
9 swaps = 0
10 for i in range(len(nums)):
11 expected = first[i // 2] if i % 2 == start else second[i // 2]
12 if nums[i] != expected:
13 swaps += 1
14 return swapsℹ
Complexity note: The optimal approach runs in linear time by counting and calculating swaps based on the counts, avoiding permutations.
- 1Count even and odd elements.
- 2Check parity difference before processing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.