Minimum Operations to Make a Uni-Value Grid

Ah, the classic “Minimum Operations to Make a Uni-Value Grid” problem! It’s like trying to convince your friends that pineapple belongs on pizza—some things just don’t add up! Imagine you have a grid filled with numbers, and you want to make all those numbers the same. Sounds simple, right? Well, it’s not just about shouting “uniformity!” at your grid. You need to perform operations, and those operations come with a cost.

In real life, this is akin to trying to get your family to agree on a single restaurant for dinner. You have to make compromises, and sometimes it feels like you’re performing operations just to keep the peace.

Problem Description

Given a 2D grid of integers and an integer x, your task is to determine the minimum number of operations required to make all the elements in the grid equal. An operation consists of selecting an element and adding or subtracting x from it. If it’s impossible to make all elements equal, return -1.

Code Solution


class Solution {
 public:
  int minOperations(vector>& grid, int x) {
    vector A;
    for (const vector& row : grid)
      A.insert(A.end(), row.begin(), row.end());
    if (ranges::any_of(A, [&](int a) { return (a - A[0]) % x; }))
      return -1;

    int ans = 0;

    nth_element(A.begin(), A.begin() + A.size() / 2, A.end());

    for (const int a : A)
      ans += abs(a - A[A.size() / 2]) / x;

    return ans;
  }
};

Approach Explanation

The code begins by flattening the 2D grid into a 1D vector. It then checks if all elements can be made equal by verifying if the difference between each element and the first element is divisible by x. If not, it returns -1.

Next, it finds the median of the array, which minimizes the total number of operations needed to make all elements equal. Finally, it calculates the total number of operations required to convert all elements to this median value.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n log n), where n is the number of elements in the grid.
Space Complexity O(n) for storing the flattened grid.

Real-World Example

Imagine you and your friends are trying to agree on a single movie to watch. Each of you has a different preference, and you can only change your choice by a certain number of genres (let’s say x genres). The goal is to find a movie that everyone can agree on with the least amount of genre shifting. If one friend is stuck on horror while another is all about rom-coms, you might find it impossible to reach a consensus.

Similar Problems

If you enjoyed this problem, you might also like: