To solve this problem, I first flattened the grid into a single list and sorted it. Then I checked whether all differences between elements and the first element are divisible by x—if not, it's impossible to make the grid uni-value and I return -1. If not, I used the median of the list as the target value (since it minimizes the total number of absolute differences), and computed the total number of operations needed by summing up abs(value - median) // x for each value.
class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
flat = [num for row in grid for num in row]
base = flat[0]
for val in flat:
if (val - base) % x != 0:
return -1
flat.sort()
median = flat[len(flat) // 2]
return sum(abs(val - median) // x for val in flat)
- Time: O(n log n)
- Space: O(n)
