Minimum Operations to Make a Uni-Value Grid

You are given an m x n integer grid and an integer x. In one operation you can add x to or subtract x from any one element. A uni-value grid is one where every element is equal. Return the minimum number of operations needed to make the grid uni-value, or -1 if it is impossible.

30:00

Minimum Operations to Make a Uni-Value Grid
medium
Free written solution
Topics
Companies

You are given an m x n integer grid and an integer x. In one operation you can add x to or subtract x from any one element. A uni-value grid is one where every element is equal. Return the minimum number of operations needed to make the grid uni-value, or -1 if it is impossible.

Example 1:
Input: {"grid":[[2,4],[6,8]],"x":2}
Output: 4
Constraints:
  • m==grid.lengthm == \text{grid.length}

  • n==grid[i].lengthn == \text{grid}[i]\text{.length}

  • 1≤m,n≤1051 \leq m, n \leq 10^5

  • 1≤m⋅n≤1051 \leq m \cdot n \leq 10^5

  • 1≤x,grid[i][j]≤1041 \leq x, \text{grid}[i][j] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[2,4],[6,8]],"x":2}

One operation adds or subtracts x = 2 from a single cell. Every cell must end on the same value, using as few operations as possible.

grid

2
4
6
8

number line

Values appear here once the grid is flattened and sorted.

x = 2

ops = 0

Variables
VariableValue
cells4
x2
DepthFunction Call
Stack empty
0/12