Skip to main content
Back to problems
#2602
Medium Algorithms

Minimum operations to make all array elements equal

Array Binary Search Sorting Prefix Sum
38.0% acceptance
Feb 25, 2026
862
29
You are given an array nums consisting of positive integers. You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times: Increase or decrease an element of the array by 1. Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i]. Note that after each query the array is reset to its original state.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>, queries: Vec<i32>) -> Vec<i64> {
    let mut sorted = nums.clone();
    sorted.sort_unstable();
    let n = sorted.len();
    let mut prefix = vec![0i64; n + 1];
    for i in 0..n {
      prefix[i + 1] = prefix[i] + sorted[i] as i64;
    }

    queries.iter().map(|&q| {
      let q = q as i64;
      // Binary search: first index where sorted[i] >= q
      let pos = sorted.partition_point(|&x| (x as i64) < q);
      // Elements left of pos are < q: cost = q * pos - prefix[pos]
      let left_cost = q * pos as i64 - prefix[pos];
      // Elements from pos onwards are >= q: cost = (prefix[n] - prefix[pos]) - q * (n - pos)
      let right_cost = (prefix[n] - prefix[pos]) - q * (n - pos) as i64;
      left_cost + right_cost
    }).collect()
  }
}