Taro Logo

Minimum Operations to Make Array Equal

Medium
Asked by:
Brillio
0 views
Topics:
ArraysGreedy AlgorithmsBinary Search

You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).

In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.

Given an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.

Example 1:

Input: n = 3
Output: 2
Explanation: arr = [1, 3, 5]
First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].

Example 2:

Input: n = 6
Output: 9

Constraints:

  • 1 <= n <= 104

Solution


Brute Force Solution

Approach

Imagine you have a row of items with different sizes, and you want to make them all completely equal by repeatedly growing some items and shrinking others. The brute force approach involves testing every single possible target size to see which one requires the least amount of total adjusting.

Here's how the algorithm would work step-by-step:

  1. Start by guessing a possible target size for all your items.
  2. Go through each item one by one and calculate how much you need to add or subtract to make it match your current guessed target size.
  3. Add up all these changes to find the total amount of effort required for this specific guess.
  4. Write down this total effort and then pick a completely different target size to test.
  5. Repeat the process of adjusting every item and calculating the total effort for every other possible target size you can think of.
  6. Compare the total effort from all your different guesses.
  7. Finally, choose the target size that resulted in the smallest overall amount of effort.

Code Implementation

def min_operations(array_length):
    # We generate the array elements using the problem's mathematical definition based on the given length
    initial_array = [(2 * index) + 1 for index in range(array_length)]

    minimum_effort = float('inf')

    # We test every possible target size to find the one that requires the absolute minimum total effort
    for candidate_target in initial_array:
        current_total_effort = 0

        for current_item in initial_array:
            current_total_effort += abs(current_item - candidate_target)

        if current_total_effort < minimum_effort:
            minimum_effort = current_total_effort

    # We divide by two because each operation increments one element and decrements another simultaneously
    return minimum_effort // 2

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach requires guessing each possible target size and then iterating through all n items to calculate the total adjustment effort. Since there are n different possible target sizes to test, and each guess involves processing all n items, the algorithm performs n multiplied by n iterations. This results in approximately n * n operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute-force algorithm only requires a few primitive variables, such as a loop counter and a running sum to track the total effort for each guessed target size. No extra data structures, temporary lists, or recursive calls are created during the process. Therefore, the auxiliary space remains constant regardless of the input size N representing the number of items in the array.

Optimal Solution

Approach

Instead of changing each number one by one, we can use a mathematical shortcut to figure out how many total steps are needed. By looking at how the numbers grow symmetrically from the middle, we can instantly calculate the total effort required without doing heavy simulation.

Here's how the algorithm would work step-by-step:

  1. Picture a row of items starting from a small baseline value and growing larger step by step as you move forward.
  2. Notice that the goal is to make all these items meet at a single target value right in the middle of the sequence.
  3. Observe that whatever amount you need to add to the items in the first half to reach the target is exactly the same amount you need to take away from the items in the second half.
  4. Focus only on the items sitting in the first half of the sequence.
  5. Figure out how far each item in the first half is from the target middle value.
  6. Add up all those distances together to get the total number of changes needed.
  7. Multiply or calculate this efficiently based on the total count of items, bypassing the need to change anything manually.

Code Implementation

def min_operations(array_length):
    # We calculate the target middle value that all elements will eventually reach.
    target_middle_value = array_length // 2

    # The total operations equal the sum of distances from the first half elements to the target.
    if array_length % 2 == 0:
        total_operations = target_middle_value * target_middle_value
    else:
        total_operations = target_middle_value * (target_middle_value + 1)

    # Returning the computed total operations directly bypasses the need for manual simulation.
    return total_operations

Big(O) Analysis

Time Complexity
O(1) – The described mathematical approach bypasses simulation and directly calculates the result based on the input size n. Instead of iterating through the elements or building the array, it evaluates a closed-form algebraic formula. Since computing this formula takes a constant number of arithmetic operations regardless of how large n is, the runtime remains strictly constant.
Space Complexity
O(1) – The algorithm relies entirely on a mathematical formula to calculate the total operations without storing any intermediate sequences, arrays, or recursive call frames. We only use a few constant scalar variables to hold the input size N and intermediate arithmetic results. As the input size N grows larger, the extra memory required remains constant. Therefore, the auxiliary space complexity simplifies to O(1).

Edge Cases

Minimum input where n equals 1
How to Handle:
The mathematical formula returns zero operations since an array of a single element is already completely equal.
Even values of n
How to Handle:
The median of the array falls strictly between the two middle elements, which is handled correctly by summing the first n/2 odd integers.
Odd values of n
How to Handle:
The median is the exact middle element of the array, allowing the formula to cleanly split operations into symmetric halves.
Maximum sized inputs up to constraint limits like n = 10^9
How to Handle:
Using an O(1) mathematical formula instead of generating the array prevents memory limit exceed and time limit exceed errors.
Integer overflow during calculation for large n
How to Handle:
Casting the multiplication result to 64-bit integers prevents overflow issues in languages with strict numeric bounds.
Negative values of n
How to Handle:
The problem constraints typically specify positive integers starting from 1, but conditional checks can safely return zero for non-positive inputs.