Minimum Operations to Make a Uni-Value Grid Problem
Description
LeetCode Problem 2033.
You are given a 2D integer grid of size m x n and an integer x.
In one operation, you can add x to or subtract x from any element in the grid.
A uni-value grid is a grid where all the elements of it are equal.
Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.
Example 1:

Input: grid = [[2,4],[6,8]], x = 2
Output: 4
Explanation: We can make every element equal to 4 by doing the following:
- Add x to 2 once.
- Subtract x from 6 once.
- Subtract x from 8 twice.
A total of 4 operations were used.
Example 2:

Input: grid = [[1,5],[2,3]], x = 1
Output: 5
Explanation: We can make every element equal to 3.
Example 3:

Input: grid = [[1,2],[3,4]], x = 2
Output: -1
Explanation: It is impossible to make every element equal.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10^51 <= m * n <= 10^51 <= x, grid[i][j] <= 10^4
Solution
Approach: Greedy with the median
One operation changes a value by x, so all values must have the same remainder modulo x. If they do not, the answer is -1.
Otherwise, put all the values in one array and sort it. The target that needs the fewest steps is the median, because moving the target away from it makes more elements farther than closer. The answer is the sum of |v - median| / x over all values.
The time complexity is O(mn log(mn)) and the space complexity is O(mn), where m and n are the numbers of rows and columns.
class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
nums = []
mod = grid[0][0] % x
for row in grid:
for v in row:
if v % x != mod:
return -1
nums.append(v)
nums.sort()
mid = nums[len(nums) >> 1]
return sum(abs(v - mid) // x for v in nums)