Minimum Operations to Make a Uni-Value Grid - 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.

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

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

Input & Output

Example 1 — Basic Case
$ Input: grid = [[2,4],[6,8]], x = 2
Output: 4
💡 Note: All elements have remainder 0 when divided by 2. Using median 4 as target: |2-4|/2 + |4-4|/2 + |6-4|/2 + |8-4|/2 = 1 + 0 + 1 + 2 = 4 operations
Example 2 — Impossible Case
$ Input: grid = [[1,5],[2,3]], x = 2
Output: -1
💡 Note: Elements have different remainders when divided by 2: 1%2=1, 5%2=1, 2%2=0, 3%2=1. Since not all elements have the same remainder, it's impossible to make them all equal.
Example 3 — Single Element
$ Input: grid = [[5]], x = 3
Output: 0
💡 Note: Grid already has single value, so it's already uni-value. No operations needed.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m * n ≤ 105
  • 1 ≤ grid[i][j], x ≤ 104

Visualization

Tap to expand
Minimum Operations to Make a Uni-Value Grid INPUT 2 4 6 8 2x2 Grid grid = [[2,4],[6,8]] x = 2 Operation: +2 or -2 Flatten: [2, 4, 6, 8] Sorted array ALGORITHM STEPS 1 Check Feasibility All (a[i]-a[0]) % x == 0? (4-2)%2=0, (6-2)%2=0 OK 2 Flatten and Sort [2, 4, 6, 8] Already sorted 3 Find Median n=4, median at index 2 Median value = 4 or 6 4 Calculate Operations Target = 4 (median) |2-4|/2 = 1 op |4-4|/2 = 0 op |6-4|/2 = 1 op |8-4|/2 = 2 op FINAL RESULT 4 4 4 4 Uni-Value Grid! Operations breakdown: 2 --> 4: +2 (1 op) 6 --> 4: -2 (1 op) 8 --> 4: -4 (2 ops) Output: 4 Total operations Key Insight: The median minimizes the sum of absolute differences. For this problem, we convert all elements to the median value. First verify all elements have same remainder when divided by x (else return -1). Then sum |element - median| / x for total operations. TutorialsPoint - Minimum Operations to Make a Uni-Value Grid | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen