Minimum Operations to Make Array Equal - Problem

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.

Input & Output

Example 1 — Even Length Array
$ Input: n = 3
Output: 2
💡 Note: Array is [1,3,5]. Target is 3. Element 1 needs +2, element 5 has excess 2. Operations: 2.
Example 2 — Larger Even Array
$ Input: n = 6
Output: 9
💡 Note: Array is [1,3,5,7,9,11]. Target is 6. Excess from second half: (7-6)+(9-6)+(11-6) = 1+3+5 = 9.
Example 3 — Single Element
$ Input: n = 1
Output: 0
💡 Note: Array is [1]. Only one element, already equal. No operations needed.

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Minimum Operations to Make Array Equal INPUT arr[i] = (2 * i) + 1 n = 3 Initial Array: i=0 i=1 i=2 1 3 5 Target (mean) = n = 3 Value Distribution: 3 Input: n = 3 ALGORITHM STEPS 1 Find Target Mean = n = 3 2 Compare Elements 1 needs +2, 5 needs -2 3 Sum Differences Only count half (pairs) 4 Apply Formula ops = n*n/4 Operations: 5 --> 4 (-1) 2 (+1) 4 --> 3 (-1) 3 (+1) n=3: 3*3/4 = 2 (integer division) FINAL RESULT Final Array (all equal): 3 3 3 = = All values at target: 3 OK - Balanced! Output: 2 operations needed Key Insight: The array is symmetric around the mean (n). Each operation transfers 1 unit from a larger element to a smaller one. The formula n*n/4 gives minimum operations: for odd n, it's (n*n-1)/4, and for even n, it's n*n/4. Time: O(1), Space: O(1). TutorialsPoint - Minimum Operations to Make Array Equal | Optimal Solution O(1)
Asked in
Google 15 Microsoft 12
32.0K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen