#2170
Minimum Operations to Make the Array Alternating
MediumArrayHash TableGreedyCountingHash 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)
The optimal approach leverages the frequency of numbers at even and odd indices to minimize changes. By maximizing the count of the most frequent elements at these indices, we can reduce the number of operations needed.
⚙️
Algorithm
3 steps- 1Step 1: Create two frequency maps: one for elements at even indices and one for odd indices.
- 2Step 2: Identify the most frequent elements in both maps and their counts.
- 3Step 3: Calculate the minimum operations needed by considering the most frequent elements at even and odd indices, ensuring they are different.
solution.py18 lines
1# Full working Python code
2from collections import Counter
3
4def min_operations_optimal(nums):
5 even_count = Counter(nums[i] for i in range(0, len(nums), 2))
6 odd_count = Counter(nums[i] for i in range(1, len(nums), 2))
7 even_most_common = even_count.most_common(2)
8 odd_most_common = odd_count.most_common(2)
9 even1, even1_count = even_most_common[0] if even_most_common else (None, 0)
10 even2, even2_count = even_most_common[1] if len(even_most_common) > 1 else (None, 0)
11 odd1, odd1_count = odd_most_common[0] if odd_most_common else (None, 0)
12 odd2, odd2_count = odd_most_common[1] if len(odd_most_common) > 1 else (None, 0)
13
14 if even1 != odd1:
15 return len(nums) - (even1_count + odd1_count)
16 else:
17 return min(len(nums) - (even1_count + odd2_count), len(nums) - (even2_count + odd1_count))
18ℹ
Complexity note: This complexity is linear because we only traverse the array a couple of times to build frequency maps and then sort them, which is efficient given the constraints.
- 1Maximize the frequency of elements at even and odd indices to minimize changes.
- 2Ensure that the most frequent elements at even and odd indices are different.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.