Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 26, 2025 21:38
Show Gist options
  • Save tatsuyax25/9b694a89326090f2aa2cb7108eb18e83 to your computer and use it in GitHub Desktop.
Save tatsuyax25/9b694a89326090f2aa2cb7108eb18e83 to your computer and use it in GitHub Desktop.
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 operation
/**
* This function calculates the minimum number of operations needed
* to transform a 2D grid into a uniform grid based on a given step size.
* If it's not possible, it returns -1.
*
* @param {number[][]} grid - The input 2D grid of numbers.
* @param {number} x - The step size for allowed operations.
* @return {number} The minimum number of operations, or -1 if not possible.
*/
var minOperations = function(grid, x) {
// Flatten the 2D array into a 1D array and sort it in ascending order.
let arr = grid.flat().sort((a, b) => a - b);
let len = arr.length;
// Determine the median value of the sorted array (target number).
let mid = arr[Math.floor(len / 2)];
// Validate if transforming the grid is possible.
// Check if the difference between consecutive elements is divisible by x.
for (let i = 1; i < len; i++) {
if ((arr[i] - arr[i - 1]) % x !== 0) return -1;
}
// Calculate the total number of operations needed.
let ans = 0;
for (let i = 0; i < len; i++) {
ans += Math.abs(arr[i] - mid) / x; // Number of steps to move each value to the median.
}
return ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment