Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: nums = [2,4,6,5,7]
Output: 3
Explanation:
Swapping 5 and 6, the array becomes [2,4,5,6,7]
Swapping 5 and 4, the array becomes [2,5,4,6,7]
Swapping 6 and 7, the array becomes [2,5,4,7,6]. The array is now a valid arrangement. Thus, the answer is 3.
Example 2:
Input: nums = [2,4,5,7]
Output: 1
Explanation:
By swapping 4 and 5, the array becomes [2,5,4,7], which is a valid arrangement. Thus, the answer is 1.
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation:
The array is already a valid arrangement. Thus, no operations are needed.
Example 4:
Input: nums = [4,5,6,8]
Output: -1
Explanation:
No valid arrangement is possible. Thus, the answer is -1.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109nums are distinct.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[2,4,6,5,7]
[2,4,5,7]
[1,2,3]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3587: Minimum Adjacent Swaps to Alternate Parity
class Solution {
private List<Integer>[] pos = new List[2];
private int[] nums;
public int minSwaps(int[] nums) {
this.nums = nums;
Arrays.setAll(pos, k -> new ArrayList<>());
for (int i = 0; i < nums.length; ++i) {
pos[nums[i] & 1].add(i);
}
if (Math.abs(pos[0].size() - pos[1].size()) > 1) {
return -1;
}
if (pos[0].size() > pos[1].size()) {
return calc(0);
}
if (pos[0].size() < pos[1].size()) {
return calc(1);
}
return Math.min(calc(0), calc(1));
}
private int calc(int k) {
int res = 0;
for (int i = 0; i < nums.length; i += 2) {
res += Math.abs(pos[k].get(i / 2) - i);
}
return res;
}
}
// Accepted solution for LeetCode #3587: Minimum Adjacent Swaps to Alternate Parity
func minSwaps(nums []int) int {
pos := [2][]int{}
for i, x := range nums {
pos[x&1] = append(pos[x&1], i)
}
if abs(len(pos[0])-len(pos[1])) > 1 {
return -1
}
calc := func(k int) int {
res := 0
for i := 0; i < len(nums); i += 2 {
res += abs(pos[k][i/2] - i)
}
return res
}
if len(pos[0]) > len(pos[1]) {
return calc(0)
}
if len(pos[0]) < len(pos[1]) {
return calc(1)
}
return min(calc(0), calc(1))
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #3587: Minimum Adjacent Swaps to Alternate Parity
class Solution:
def minSwaps(self, nums: List[int]) -> int:
def calc(k: int) -> int:
return sum(abs(i - j) for i, j in zip(range(0, len(nums), 2), pos[k]))
pos = [[], []]
for i, x in enumerate(nums):
pos[x & 1].append(i)
if abs(len(pos[0]) - len(pos[1])) > 1:
return -1
if len(pos[0]) > len(pos[1]):
return calc(0)
if len(pos[0]) < len(pos[1]):
return calc(1)
return min(calc(0), calc(1))
// Accepted solution for LeetCode #3587: Minimum Adjacent Swaps to Alternate Parity
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3587: Minimum Adjacent Swaps to Alternate Parity
// class Solution {
// private List<Integer>[] pos = new List[2];
// private int[] nums;
//
// public int minSwaps(int[] nums) {
// this.nums = nums;
// Arrays.setAll(pos, k -> new ArrayList<>());
// for (int i = 0; i < nums.length; ++i) {
// pos[nums[i] & 1].add(i);
// }
// if (Math.abs(pos[0].size() - pos[1].size()) > 1) {
// return -1;
// }
// if (pos[0].size() > pos[1].size()) {
// return calc(0);
// }
// if (pos[0].size() < pos[1].size()) {
// return calc(1);
// }
// return Math.min(calc(0), calc(1));
// }
//
// private int calc(int k) {
// int res = 0;
// for (int i = 0; i < nums.length; i += 2) {
// res += Math.abs(pos[k].get(i / 2) - i);
// }
// return res;
// }
// }
// Accepted solution for LeetCode #3587: Minimum Adjacent Swaps to Alternate Parity
function minSwaps(nums: number[]): number {
const pos: number[][] = [[], []];
for (let i = 0; i < nums.length; ++i) {
pos[nums[i] & 1].push(i);
}
if (Math.abs(pos[0].length - pos[1].length) > 1) {
return -1;
}
const calc = (k: number): number => {
let res = 0;
for (let i = 0; i < nums.length; i += 2) {
res += Math.abs(pos[k][i >> 1] - i);
}
return res;
};
if (pos[0].length > pos[1].length) {
return calc(0);
}
if (pos[0].length < pos[1].length) {
return calc(1);
}
return Math.min(calc(0), calc(1));
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.