Skip to main content
impol.dev

Minimum Operations to Make a Uni-Value Grid

Medium

You receive 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 .

A uni-value grid is a grid where all the elements of it are equal.

Produce the minimum number of operations to make the grid uni-value . If it is not possible, return -1 .

Example 1

Original illustrative diagram 1 for Minimum Operations to Make a Uni-Value Grid

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.

Example 2

Original illustrative diagram 2 for Minimum Operations to Make a Uni-Value Grid

Input: grid = [[1,5],[2,3]], x = 1

Output: 5

Explanation: We can make every element equal to 3.

Example 3

Original illustrative diagram 3 for Minimum Operations to Make a Uni-Value Grid

Input: grid = [[1,2],[3,4]], x = 2

Output: -1

Explanation: It is impossible to make every element equal.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10^5
  • 1 <= m * n <= 10^5
  • 1 <= x, grid[i][j] <= 10^4

Did this problem appear in one of your interviews?

Responses stay private.

Acceptance rate: 0%

© 2026 impol.dev. All rights reserved.PrivacyTerms