Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Adding or subtracting x preserves a value's remainder modulo x, so all cells must share a remainder. When they do, choosing a common target minimizes a sum of absolute distances, whose optimum is a median. Dividing each distance by x converts it into operation count.

Approach

Collect the grid values and verify their common remainder, returning -1 on a mismatch. Python checks while collecting; JavaScript flattens first. Sort the values and choose the middle value, using the upper median for an even count. Sum the exact quotients abs(value - median) / x and return the total. Python uses integer division and JavaScript ordinary division; the shared remainder guarantees every quotient is an integer and every cell can reach the chosen median.

class Solution: def minOperations(self, grid: List[List[int]], x: int) -> int: n = len(grid) m = len(grid[0]) arr = [] rem = -1 for i in range(n): for j in range(m): if rem == -1: rem = grid[i][j] % x if grid[i][j] % x != rem: return -1 arr.append(grid[i][j]) arr.sort() mid = arr[len(arr) // 2] res = 0 for val in arr: res += abs(val - mid) // x return res

Complexity analysis

Let N = rows * columns. Time: O(N log N) to flatten, validate remainders, sort, and sum distances to the median. Auxiliary space: O(N) for the flattened values and sorting workspace.