Minimum Operations to Make a Uni-Value Grid (LeetCode 2033): Solution and Explanation

Medium
Array
Math
Sorting
Matrix

Each operation moves one grid value up or down by x. Return the fewest operations that make every value equal, or -1 if no number of operations can.

Intuition

Where a value sits in the grid does not matter, only the value itself. So the grid is really just a list of numbers.

Adding or subtracting x keeps v % x the same. Two values with different remainders can never meet, so if any remainder differs from the rest, the answer is -1.

When all remainders match, moving v to a target t takes exactly |v - t| / x operations. Dividing every distance by the same x does not change which target is best, so the question becomes: which t minimizes the total distance to all values?

That point is the median. Moving t right past the median brings it closer to fewer than half the values and farther from more than half, so the total can only grow. The median is also one of the values, so it shares their remainder and is reachable.

Approach: Remainder check, then median

  1. Flatten the grid into a list vals and sort it.
  2. Let rem = vals[0] % x. If any value has v % x != rem, return -1.
  3. Pick median = vals[len(vals) // 2].
  4. Add |v - median| / x for every value and return the sum.

Step-by-step example

grid = [[2,4],[6,8]], x = 2
  1. Flatten and sort: vals = [2, 4, 6, 8].
  2. 2 % 2 = 0, and 4, 6 and 8 also leave remainder 0, so a common value is reachable.
  3. median = vals[2] = 6.
  4. 2 needs (6 - 2) / 2 = 2 steps, 4 needs 1, 6 needs 0 and 8 needs 1. Total ops = 4.
  5. Return 4. Choosing 4 as the target gives the same total, because any point between the two middle values is optimal.

Code: Python, Java, C++

1class Solution:
2    def minOperations(self, grid: List[List[int]], x: int) -> int:
3        vals = sorted(v for row in grid for v in row)
4        rem = vals[0] % x
5        for v in vals:
6            if v % x != rem:
7                return -1
8        median = vals[len(vals) // 2]
9        ops = 0
10        for v in vals:
11            ops += abs(v - median) // x
12        return ops
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n * log(m * n))

Sorting the m * n values dominates. The remainder check and the final sum are single linear passes.

Space

O(m * n)

The flattened list holds every value of the grid.

Other approaches

Quickselect for the median (time O(m * n) on average, space O(m * n))

Find the middle element with quickselect (for example nth_element in C++) instead of a full sort. The remainder check and sum do not need sorted order.

Counting sort (time O(m * n + 10^4), space O(10^4))

Values are at most 10^4, so a count array finds the median by walking the counts until half the cells are covered.

Try every target with prefix sums (time O(m * n * log(m * n)), space O(m * n))

Sort, build prefix sums, and evaluate the cost of each value as the target in O(1). Correct, but it does more work than simply picking the median.

Common mistakes

  • Using the mean instead of the median. The mean minimizes squared distance, not absolute distance, and it may not even share the values' remainder.
  • Checking only that max - min is divisible by x. Every pair of values must differ by a multiple of x, which is exactly the shared-remainder test.
  • Forgetting to divide by x. The distance |v - median| counts units, but each operation covers x units.
  • Comparing v % x against 0 instead of against the first value's remainder. The values may all share a remainder other than 0.

Frequently asked questions

Why the median and not the average?

The sum of absolute distances changes by (values on the left) minus (values on the right) for each unit you move the target right. That change is negative until the target passes the middle value and positive after, so the minimum is at the median.

With an even number of values, which middle element should I use?

Either one. Every target between the two middle values gives the same total, so vals[len // 2] works.

Can the answer overflow a 32-bit int?

No. There are at most 10^5 values and each moves at most 10^4 steps, so the total is at most 10^9.