2033. Minimum Operations to Make a Uni-Value Grid
UnknownView on LeetCode
Problem Overview
Minimum Operations to Make a Uni-Value Grid (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Math pattern in coding interviews. Flatten grid; check all values share same remainder mod x; sort and use median as target.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Flatten grid; check all values share same remainder mod x; sort and use median as target.
2033.cs
C#
// Approach: Flatten grid; check all values share same remainder mod x; sort and use median as target.
// Time: O(mn log(mn)) Space: O(mn)
public class Solution
{
public int MinOperations(int[][] grid, int x)
{
int m = grid.Length;
int n = grid[0].Length;
int[] arr = new int[m * n];
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
arr[i * n + j] = grid[i][j];
}
if (arr.Any(a => (a - arr[0]) % x != 0))
return -1;
int ans = 0;
Array.Sort(arr);
foreach (var a in arr)
ans += Math.Abs(a - arr[arr.Length / 2]) / x;
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)