algoadvance

Leetcode 3127. Make a Square with the Same Color

Problem Statement

You are given a matrix grid of size n x n filled with integers from 1 to 10 representing different colors. Your task is to determine the minimum number of recoloring operations needed to turn this n x n grid into an n x n grid where every element in the grid has the same color.

Clarifying Questions

  1. Input constraints:
    • What is the range of n? (1 <= n <= 50)
    • Can we assume the grid will always have at least one element?
  2. Output:
    • Do we need to return the minimum number of operations, or should we also return the final grid? (Return only the minimum number of operations.)
  3. Operations:
    • Are we allowed to recolor any cell in one operation?

Given the constraints, let’s proceed to outline the solution.

Strategy

To determine the minimum recoloring operations:

  1. Count Colors:
    • We’ll count the frequency of each color in the grid.
  2. Identify Target Color:
    • The optimal color to recolor the entire grid to will be the color that already has the highest frequency.
  3. Calculate Operations:
    • Calculate the minimum number of operations needed to change all the cells in the grid to this most frequent color.

Code

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int minOperationsToOneColor(vector<vector<int>>& grid) {
    unordered_map<int, int> colorCount;
    int n = grid.size();
    
    // Count the frequency of each color in the grid
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            colorCount[grid[i][j]]++;
        }
    }
    
    // Find the color with the maximum frequency
    int maxColorFrequency = 0;
    for (const auto& entry : colorCount) {
        if (entry.second > maxColorFrequency) {
            maxColorFrequency = entry.second;
        }
    }
    
    // The minimum number of operations needed is to convert
    // all other cells to the color with the highest frequency.
    return n * n - maxColorFrequency;
}

int main() {
    vector<vector<int>> grid = {
        {1, 2, 1},
        {1, 3, 2},
        {3, 2, 1}
    };
    
    cout << "Minimum operations to make the grid one color: " 
         << minOperationsToOneColor(grid) << endl;
    
    return 0;
}

Time Complexity

This approach ensures that we efficiently determine the minimum number of recoloring operations required to make the grid uniform in color.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI