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 = 1
›
Output:
-1
💡 Note:
Elements have different remainders: 1%1=0, 5%1=0, 2%1=0, 3%1=0. Actually all are 0, so it's possible. Let me recalculate: all can reach any value, minimum ops = 0
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
Understanding the Visualization
1
Input Grid
2D grid with different values and step size x
2
Check Feasibility
All elements must have same remainder mod x
3
Find Optimal Target
Use median to minimize total operations
Key Takeaway
🎯 Key Insight: Use the median as target value since it minimizes the sum of absolute deviations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code