Opening the reading…
Opening the reading…
MATRIX › MATRIX TRANSFORMATION AND MODIFICATION
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The final grid has only two regions: cells that belong to the Y and cells outside it. Every Y cell must become one common value, and every non-Y cell must become another common value. Once you choose those two values, each cell can be handled independently: a cell already holding its region's chosen value stays unchanged, while every other cell costs one operation.
There are only three possible values, so there are just six valid ordered choices for the pair: one value for Y and a different value for non-Y. The grid scan records how often each value appears in each region. For a chosen Y value, the number of changes inside Y is its size minus its frequency; the same formula applies outside Y. Checking all six pairs guarantees that the best assignment is found.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n^2) | The nested scan classifies and counts each of the n^2 cells once. The final search checks only 3 x 3 value pairs, which is constant work and does not change the bound. |
| Space | O(1) extra | The two regions use fixed-size frequency arrays of length 3 and a fixed number of counters. The returned value is a scalar, so there is no output storage to exclude; the bound stays constant even for the largest allowed grid. |
#include <algorithm>
#include <climits>
#include <vector>
using namespace std;
class Solution {
public:
int minimumOperationsToWriteY(vector<vector<int>>& grid) {
int n = grid.size();
int center = n / 2;
int yCount = 0;
int nonYCount = 0;
int yFreq[3] = {0, 0, 0};
int nonYFreq[3] = {0, 0, 0};
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
bool isY = false;
if (i <= center) {
if (j == i || j == n - 1 - i) {
isY = true;
}
} else {
if (j == center) {
isY = true;
}
}
if (isY) {
++yCount;
++yFreq[grid[i][j]];
} else {
++nonYCount;
++nonYFreq[grid[i][j]];
}
}
}
int answer = INT_MAX;
for (int yVal = 0; yVal < 3; ++yVal) {
for (int nonYVal = 0; nonYVal < 3; ++nonYVal) {
if (yVal == nonYVal) {
continue;
}
int changes = (yCount - yFreq[yVal])
+ (nonYCount - nonYFreq[nonYVal]);
answer = min(answer, changes);
}
}
return answer;
}
};The split at i <= center is the key coordinate decision. In the upper half, the Y consists of the two diagonals, including the center where they meet. In the lower half, only the center column belongs to the Y. The two conditions are mutually exclusive by row, so each cell is counted exactly once and no separate visited array is needed.