Skip to main content
Back to problems
#2033
Medium Algorithms

Minimum operations to make a uni value grid

Array Math Sorting Matrix
67.5% acceptance
Feb 25, 2026
1109
75
You are given a 2D integer grid and an integer x. In one operation, you can add x to or subtract x from any element. A uni-value grid is a grid where all elements are equal. Return the minimum number of operations to make the grid uni-value. Return -1 if impossible.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(grid: Vec<Vec<i32>>, x: i32) -> i32 {
    let mut vals: Vec<i32> = grid.into_iter().flatten().collect();
    let r = vals[0] % x;
    for &v in &vals {
      if v % x != r { return -1; }
    }
    vals.sort();
    let median = vals[vals.len() / 2];
    vals.iter().map(|&v| (v - median).abs() / x).sum()
  }
}