Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1551. Minimum Operations to Make Array Equal - Leetcode Solution

Code Implementation

class Solution:
    def minOperations(self, n: int) -> int:
        # The array will be [1, 3, 5, ..., 2n-1]
        # The target value is n
        # The minimal number of moves is sum(abs(arr[i] - n)) for i in range(n)
        # This simplifies to n^2 // 4
        return (n * n) // 4
      
class Solution {
public:
    int minOperations(int n) {
        // The minimal number of moves is n^2 / 4
        return (n * n) / 4;
    }
};
      
class Solution {
    public int minOperations(int n) {
        // The minimal number of moves is n^2 / 4
        return (n * n) / 4;
    }
}
      
var minOperations = function(n) {
    // The minimal number of moves is n^2 / 4
    return Math.floor(n * n / 4);
};
      

Problem Description

You are given an integer n. Consider an array arr of length n where arr[i] = 2 * i + 1 for 0 ≤ i < n. In other words, the array contains the first n odd numbers: [1, 3, 5, ..., 2n-1].

In one operation, you can choose any two indices and increase the value at one index by 1 while decreasing the value at the other index by 1. Your goal is to make all elements in the array equal using the minimum number of such operations.

Return the minimum number of operations required to make all elements of arr equal.

Thought Process

At first glance, it seems we might need to simulate the process, repeatedly picking the largest and smallest elements and adjusting them until all values are equal. However, this would be inefficient for large n.

By observing the problem, we notice that:

  • Each operation preserves the sum of the array.
  • The array is symmetric and made up of consecutive odd numbers.
  • The final value each element must reach is the mean of the array, which is always n for this construction.
Instead of simulating, we can calculate how many moves it takes to bring all elements to n directly.

Solution Approach

  • Step 1: Find the target value. Since the sum is fixed, and all elements must be equal, the target is the mean of the array. For this sequence, the mean is always n.
  • Step 2: Count required moves for each element. For each element less than n, calculate how much it needs to be increased. For each element greater than n, calculate how much it needs to be decreased. Since the array is symmetric, we only need to consider one side.
  • Step 3: Sum the moves for one side. The total number of moves is the sum of differences between arr[i] and n for all i less than n//2.
  • Step 4: Formula derivation. If you work out the math, this sum always equals n^2 // 4.
  • Step 5: Return the result. This formula gives the minimum number of operations in constant time.

This approach is efficient and avoids unnecessary simulation.

Example Walkthrough

Let's use n = 5 as an example. The array is [1, 3, 5, 7, 9]. The target value is 5.

  • arr[0] = 1 needs 4 moves to reach 5
  • arr[1] = 3 needs 2 moves to reach 5
  • arr[2] = 5 is already at the target
  • arr[3] = 7 needs 2 moves to reduce to 5
  • arr[4] = 9 needs 4 moves to reduce to 5

Since each operation transfers 1 unit from a high value to a low value, we only need to sum the moves for one side:
4 + 2 = 6 moves (for indices 0 and 1).

The formula gives n^2 // 4 = 25 // 4 = 6, which matches our calculation.

Time and Space Complexity

  • Brute-force approach:
    • Simulating each move could take up to O(n^2) time, especially if we always adjust the smallest and largest values.
    • Space complexity is O(n) to store the array.
  • Optimized approach (formula):
    • Time complexity is O(1) since we only perform a multiplication and division.
    • Space complexity is O(1) as no extra space is needed.

Summary

The key insight is recognizing the symmetry and arithmetic properties of the array. By realizing that the number of operations only depends on the array length and not the actual values, we avoid unnecessary simulation. The elegant formula n^2 // 4 provides an optimal, constant-time solution.