#1551
Minimum Operations to Make Array Equal
MediumMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal solution leverages the mathematical properties of the array to directly calculate the number of operations needed without simulating each operation. This drastically reduces the time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total sum of the array, which is n * n (since arr[i] = (2 * i) + 1).
- 2Step 2: Determine the target value, which is the average of the array: target = sum(arr) / n.
- 3Step 3: Calculate the number of operations needed by summing the differences of elements greater than the target divided by 2 (since each operation balances two elements).
solution.py2 lines
1def minOperations(n):
2 return (n // 2) * (n // 2) if n % 2 == 0 else (n // 2) * (n // 2 + 1)ℹ
Complexity note: The time complexity is O(1) because we are performing a constant number of arithmetic operations regardless of the size of n.
- 1The sum of the array must be evenly divisible by n for all elements to be equal.
- 2Each operation adjusts two elements, so the total number of operations is half the total difference.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.