#3854
Minimum Operations to Make Array Parity Alternating
MediumArrayGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of generating patterns, directly calculate the operations needed to adjust each element to fit either of the two required patterns. This reduces unnecessary computations.
⚙️
Algorithm
3 steps- 1Step 1: Count operations needed to convert nums to fit the 'even, odd, even...' pattern.
- 2Step 2: Count operations needed to convert nums to fit the 'odd, even, odd...' pattern.
- 3Step 3: Return the minimum operations and calculate max(nums) - min(nums) for the resulting array.
solution.py10 lines
1def min_operations(nums):
2 even_ops, odd_ops = 0, 0
3 for i, num in enumerate(nums):
4 if i % 2 == 0:
5 even_ops += num % 2
6 odd_ops += (num + 1) % 2
7 else:
8 even_ops += (num + 1) % 2
9 odd_ops += num % 2
10 return [min(even_ops, odd_ops), max(nums) - min(nums)]ℹ
Complexity note: The complexity is O(n) because we only traverse the array once to calculate operations and find min/max values.
- 1Parity must alternate between even and odd.
- 2Each element's parity can be fixed with a single operation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.