DDSA Solutions

2033. Minimum Operations to Make a Uni-Value Grid

Advertisement

Approach

Flatten grid; check all values share same remainder mod x; sort and use median as target.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Math

Math problems test number theory, combinatorics, and modular arithmetic. Common tools: GCD/LCM (Euclidean algorithm), prime sieve, modular inverse (Fermat's little theorem), digit manipulation, and bit tricks. Overflow is a key concern in C# — use long when products may exceed 2³¹.

Greedy

Greedy algorithms make locally optimal choices at each step, hoping to reach a global optimum. Greedy works when a problem has the "greedy choice property" and "optimal substructure". Common applications: interval scheduling, activity selection, Huffman coding, and jump game.

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;
    }
}
Advertisement
Was this solution helpful?