Minimum Operations to Make All Array Elements Equal

For each query, sort once and use prefix sums plus binary search to compute the total deviation.

Medium
Time O((n + q) log n) Space O(n)
LeetCode
5 min read
prefix-sum binary-search sorting

Problem#

For each query q, return the minimum number of unit operations (each increments or decrements one element by 1) to make every element of nums equal to q. Answer each query independently.

Examples#

  • nums = [3,1,6,8], queries = [1,5][14,10]
  • nums = [2,9,6,3], queries = [10][20]

Constraints#

  • 1 <= nums.length, queries.length <= 10^5, 1 <= nums[i], queries[i] <= 10^9.

Approach#

Sort nums and build a prefix sum. For query q, find the split index where elements switch from <= q to > q via upper_bound. The cost is (q * k - leftSum) + (rightSum - q * (n - k)).

Solution#

Minimum Operations to Make All Array Elements Equal
class Solution {
public:
vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<long long> pref(n + 1, 0);
for (int i = 0; i < n; ++i) pref[i + 1] = pref[i] + nums[i];
vector<long long> ans;
ans.reserve(queries.size());
for (int q : queries) {
int k = upper_bound(nums.begin(), nums.end(), q) - nums.begin();
long long left = (long long)q * k - pref[k];
long long right = (pref[n] - pref[k]) - (long long)q * (n - k);
ans.push_back(left + right);
}
return ans;
}
};

Editorial#

For each split point, every element below contributes q - x and every element above contributes x - q. Prefix sums collapse those summations into O(1) per query after O(n log n) preprocessing.

Complexity#

  • Time: O((n + q) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.