Leetcode #2033: Minimum Operations to Make a Uni-Value Grid
In this guide, we solve Leetcode #2033 Minimum Operations to Make a Uni-Value Grid in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Math, Matrix, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
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.
Python Solution
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)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.