Minimum Operations to Make a Uni-Value Grid — LeetCode 2033 Python Solution

MediumArrayMathMatrixSorting
Problem
#2033
Reading time
2 min

The problem

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.

Example

Input
grid = [[2,4],[6,8]], x = 2
Output
4
Explanation
We can make every element equal to 4 by doing the following:

Python solution

Python
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

MeasureComplexity
TimeO((m \times n) \times \log (m \times n))
SpaceO(m \times n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2033. Minimum Operations to Make a Uni-Value Grid is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2033. Minimum Operations to Make a Uni-Value Grid?
LeetCode 2033. Minimum Operations to Make a Uni-Value Grid is rated Medium on LeetCode.
What is the time complexity of LeetCode 2033. Minimum Operations to Make a Uni-Value Grid?
The Python solution on this page runs in O((m \times n) \times \log (m \times n)).
What is the space complexity of LeetCode 2033. Minimum Operations to Make a Uni-Value Grid?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 2033. Minimum Operations to Make a Uni-Value Grid cover?
LeetCode 2033. Minimum Operations to Make a Uni-Value Grid is tagged Array, Math, Matrix and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview