Skip to main content

Matrix

Minimum Operations to Write the Letter Y on a Grid Solution In C++/Python/java/JS

Minimum Operations to Write the Letter Y on a Grid Problem Description:

You are given a 0-indexed n x n grid where n is odd, and grid[r][c] is 0, 1, or 2.
We say that a cell belongs to the Letter Y if it belongs to one of the following:
The diagonal starting at the top-left cell and ending at the center cell of the grid.
The diagonal starting at the top-right cell and ending at the center cell of the grid.
The vertical line starting at the center cell and ending at the bottom border of the grid.
The Letter Y is written on the grid if and only if:
All values at cells belonging to the Y are equal.
All values at cells not belonging to the Y are equal.
The values at cells belonging to the Y are different from the values at cells not belonging to the Y.
Return the minimum number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to 0, 1, or 2.
Minimum Operations to Write the Letter Y on a Grid-Problem-Description

Examples:

Input: grid = [[1,2,2],[1,1,0],[0,1,0]]
Output:
3
Explanation:
We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.

Input: grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
Output:
12
Explanation:
We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2.
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.

Constraints:

3 <= n <= 49
n == grid.length == grid[i].length
0 <= grid[i][j] <= 2
n is odd

Brute Force Approach

Imagine you're given an n x n grid filled with numbers — specifically just 0s, 1s, and 2s — and you're asked to transform it into a shape resembling the letter Y. But not just any Y — this Y has a strict definition:

  • It includes two diagonals from the top corners that meet at the center cell (this is the "fork" of the Y).
  • From that center cell, there's a vertical line going down to the bottom (the "tail" of the Y).

So if we visualize a 5 x 5 grid, the Y shape would include these cells:

Minimum Operations to Write the Letter Y on a Grid

All other cells — the dots (.) — are not part of the Y.

Now, your goal is to change as few cells as possible so that:

  1. Every cell in the Y has the same value (either all 0s, or all 1s, or all 2s),
  2. Every cell outside the Y also has the same value (again, either 0, 1, or 2), but,
  3. The value inside the Y must be different from the value outside.

Here's where a really important observation comes in:
The grid can only contain three possible values: 0, 1, and 2.

This is huge, because it means we don’t need to consider an infinite number of values or combinations — we can explicitly try all possibilities. So instead of guessing and checking randomly, we can structure our thinking.

Let’s think of it like this:

We are splitting the entire grid into two zones:

  • Zone 1: Cells that are part of the Y.
  • Zone 2: Cells that are not part of the Y.

We want one value for the Y zone and a different value for the non-Y zone.

So the real question becomes:
How many combinations of different values can we assign to the Y and non-Y zones?

The answer is:

  • Y = 0, non-Y = 1
  • Y = 0, non-Y = 2
  • Y = 1, non-Y = 0
  • Y = 1, non-Y = 2
  • Y = 2, non-Y = 0
  • Y = 2, non-Y = 1

That's 6 total combinations where the Y and non-Y values are distinct.

Now comes the question: how do we know which of these 6 combinations is the best?

"Best" here means: requires the fewest number of changes (operations). Because remember — you can change any cell's value to anything you want in one move, but you want to do this as little as possible.

So here’s what we do for each of the 6 combinations:

  • Go through every cell in the grid.
  • If the cell belongs to the Y:
    • Check if it already has the target Y value. If not, we’d need to change it (that’s 1 operation).
  • If the cell does NOT belong to the Y:
    • Check if it already has the target non-Y value. If not, that’s also 1 operation.

We count how many such operations would be needed for that combination.

For example:

  • Suppose we try Y = 1 and non-Y = 0.
  • Then we walk through every cell.
  • If a Y cell is already 1 — great, no change.
  • If it’s 0 or 2 — we need to change it to 1.
  • Same logic for non-Y cells needing to become 0.

We do this for all 6 combinations, count the number of required changes for each, and finally pick the minimum among them.

So let’s summarize the logic in a friendly way:

You're looking to carve out a Y shape from a grid using just two distinct numbers.
Because the grid only contains 0s, 1s, and 2s, you can brute force through all the possibilities for which number should represent the Y and which one should represent the non-Y area.

There are only 6 such combinations, and for each one, you count how many cells you'd have to change to make the grid follow the Y-pattern correctly.

Whichever combination gives you the fewest changes — that’s your answer.

It’s almost like trying on 6 different outfits and choosing the one that needs the least ironing to look good.

Let's understand with an example:

Minimum Operations to Write the Letter Y on a Grid Example:

Input:
grid = [[1,2,2],
[1,1,0],
[0,1,0]]

Step 1: Identify Y-shape cells in a 3x3 grid

For n = 3, the center is at (1,1).
Y-shape includes:

  • Diagonal (top-left to center): (0,0), (1,1)
  • Diagonal (top-right to center): (0,2), (1,1)
  • Vertical line from center down: (1,1), (2,1)

So total Y-cells: (0,0), (0,2), (1,1), (2,1)
All other cells are non-Y: (0,1), (1,0), (1,2), (2,0), (2,2)

Step 2: Try all 6 (Y, non-Y) value combinations and count operations

We go through each cell and count how many changes are needed for each case.

1. Y = 0, non-Y = 1

Y-cells should be 0: (0,0=1), (0,2=2), (1,1=1), (2,1=1)
→ Need to change (0,0), (0,2), (1,1), (2,1) → 4 changes
non-Y-cells should be 1: (0,1=2), (1,0=1), (1,2=0), (2,0=0), (2,2=0)
→ (0,1), (1,2), (2,0), (2,2) need change → 4 changes
Total = 4 + 4 = 8

2. Y = 1, non-Y = 0

Y-cells should be 1: (0,0=1), (0,2=2), (1,1=1), (2,1=1)
→ only (0,2) wrong → 1 change
non-Y-cells should be 0: (0,1=2), (1,0=1), (1,2=0), (2,0=0), (2,2=0)
→ (0,1), (1,0) need change → 2 changes
Total = 1 + 2 = 3

3. Y = 1, non-Y = 2

Y-cells: (0,0=1), (0,2=2), (1,1=1), (2,1=1)
→ (0,2) wrong → 1 change
non-Y should be 2: (0,1=2), (1,0=1), (1,2=0), (2,0=0), (2,2=0)
→ all except (0,1) need change → 4 changes
Total = 1 + 4 = 5

4. Y = 2, non-Y = 1

Y-cells: (0,0=1), (0,2=2), (1,1=1), (2,1=1)
→ (0,0), (1,1), (2,1) need change → 3
non-Y = 1: (0,1=2), (1,0=1), (1,2=0), (2,0=0), (2,2=0)
→ (0,1), (1,2), (2,0), (2,2) → 4
Total = 3 + 4 = 7

5. Y = 2, non-Y = 0

Y-cells: (0,0=1), (0,2=2), (1,1=1), (2,1=1)
→ change (0,0), (1,1), (2,1) → 3
non-Y = 0: (0,1=2), (1,0=1), (1,2=0), (2,0=0), (2,2=0)
→ (0,1), (1,0) → 2
Total = 3 + 2 = 5

6. Y = 0, non-Y = 2

Y-cells: want 0: (0,0=1), (0,2=2), (1,1=1), (2,1=1)
→ all wrong → 4
non-Y = 2: (0,1=2), (1,0=1), (1,2=0), (2,0=0), (2,2=0)
→ (1,0), (1,2), (2,0), (2,2) → 4
Total = 4 + 4 = 8

Final Answer: Minimum operations = 3 (from combination Y = 1, non-Y = 0)
So we return 3.

Steps to Implement the Solution:

Step 1: Define the isY function

  • Purpose: Check if a cell (i, j) belongs to the Y-shape in an n x n grid.
  • Logic:
    • If row i ≤ n/2 → part of the upper diagonals → check i == j or i + j == n - 1.
    • If row i > n/2 → part of the vertical tail → check j == n/2.

Step 2: Define the getOperationCount function

  • Inputs: grid, y, and notY — the values assigned to Y and non-Y cells.
  • Logic:
    • Loop over all cells.
    • If the cell is a Y-cell and its value isn’t y, increment operation count.
    • If it’s a non-Y-cell and its value isn’t notY, also increment.

Step 3: Try all 6 valid value combinations

  • Since only values are 0, 1, 2 — try all 6 distinct (y, notY) pairs:
    • (0,1), (1,0), (1,2), (2,1), (2,0), (0,2)

Step 4: Return the minimum operations

  • Call getOperationCount for each pair.
  • Return the minimum among all 6 results.

Minimum Operations to Write the Letter Y on a Grid Solution

Code Implementation / Leetcode solution of Minimum Operations to Write the Letter Y on a Grid
1. Minimum Operations to Write the Letter Y on a Grid solution in C++ Try on Compiler
class Solution {
    // Helper function to determine whether a cell is part of the Y shape
    bool isY(int n, int i, int j)
    {
        // Check for diagonal arms of Y (upper part)
        // OR vertical tail of Y (lower part)
        return (i <= n/2 && (i == j || i + j == n - 1)) || (i > n/2 && j == n/2);
    }

    // Function to count how many changes are needed to make
    // all Y cells have value 'y' and all non-Y cells have value 'notY'
    int getOperationCount(vector<vector<int>>& grid, int y, int notY){

        // Get the size of the grid
        int n = grid.size();

        // Initialize operation count
        int ans = 0;

        // Traverse each cell in the grid
        for(int i = 0; i < n; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                // If the current cell belongs to Y
                if(isY(n, i, j)){

                    // Count if its value is not equal to the target Y value
                    if(y != grid[i][j]) 
                        ans++;
                }
                // If the current cell does not belong to Y
                else{

                    // Count if its value is not equal to the target non-Y value
                    if(notY != grid[i][j]) 
                        ans++;
                }
            }
        }

        // Return the total number of operations
        return ans;
    }

public:
    // Main function to compute the minimum number of operations
    int minimumOperationsToWriteY(vector<vector<int>>& grid) {
        
        // Try all 6 combinations of (Y value, non-Y value)
        int option1 = getOperationCount(grid, 0, 1);
        int option2 = getOperationCount(grid, 1, 0);
        int option3 = getOperationCount(grid, 1, 2);
        int option4 = getOperationCount(grid, 2, 1);
        int option5 = getOperationCount(grid, 2, 0);
        int option6 = getOperationCount(grid, 0, 2);

        // Return the minimum number of changes required
        return min({option1, option2, option3, option4, option5, option6});
    }
};

2. Minimum Operations to Write the Letter Y on a Grid solution in Java Try on Compiler
class Solution {
    // Helper method to check if cell is part of the Y
    private boolean isY(int n, int i, int j) {

        // Check for diagonals (top part) and vertical (bottom part)
        return (i <= n / 2 && (i == j || i + j == n - 1)) || (i > n / 2 && j == n / 2);
    }

    // Method to compute required operations for given Y and non-Y values
    private int getOperationCount(int[][] grid, int y, int notY) {

        // Get grid size
        int n = grid.length;

        // Initialize operation counter
        int ans = 0;

        // Traverse all cells
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {

                // If part of Y and value not equal to target Y value
                if (isY(n, i, j)) {
                    if (grid[i][j] != y) ans++;
                } 

                // If not part of Y and value not equal to target non-Y value
                else {
                    if (grid[i][j] != notY) ans++;
                }
            }
        }

        // Return total operations
        return ans;
    }

    // Main function to find minimum operations
    public int minimumOperationsToWriteY(int[][] grid) {
        
        // Try all 6 value combinations
        int option1 = getOperationCount(grid, 0, 1);
        int option2 = getOperationCount(grid, 1, 0);
        int option3 = getOperationCount(grid, 1, 2);
        int option4 = getOperationCount(grid, 2, 1);
        int option5 = getOperationCount(grid, 2, 0);
        int option6 = getOperationCount(grid, 0, 2);

        // Return the minimum among them
        return Math.min(option1, Math.min(option2, Math.min(option3,
               Math.min(option4, Math.min(option5, option6)))));
    }
}

3. Minimum Operations to Write the Letter Y on a Grid solution in Python Try on Compiler
class Solution:
    # Helper to check if cell belongs to the Y
    def isY(self, n, i, j):

        # Check for diagonals (top part) and vertical (bottom part)
        return (i <= n // 2 and (i == j or i + j == n - 1)) or (i > n // 2 and j == n // 2)

    # Compute number of operations for a specific (y, nonY) combination
    def getOperationCount(self, grid, y, notY):

        # Grid size
        n = len(grid)

        # Operation counter
        ans = 0

        # Traverse all cells
        for i in range(n):
            for j in range(n):

                # If part of Y and value doesn't match y
                if self.isY(n, i, j):
                    if grid[i][j] != y:
                        ans += 1

                # If not part of Y and value doesn't match nonY
                else:
                    if grid[i][j] != notY:
                        ans += 1

        # Return total operations
        return ans

    # Main method to compute minimum operations
    def minimumOperationsToWriteY(self, grid):
        
        # Try all 6 value combinations
        option1 = self.getOperationCount(grid, 0, 1)
        option2 = self.getOperationCount(grid, 1, 0)
        option3 = self.getOperationCount(grid, 1, 2)
        option4 = self.getOperationCount(grid, 2, 1)
        option5 = self.getOperationCount(grid, 2, 0)
        option6 = self.getOperationCount(grid, 0, 2)

        # Return the minimum of them
        return min(option1, option2, option3, option4, option5, option6)

4. Minimum Operations to Write the Letter Y on a Grid solution in Javascript Try on Compiler
/**
 * @param {number[][]} grid
 * @return {number}
 */
var minimumOperationsToWriteY = function(grid) {
    // Helper function to check if a cell (i, j) belongs to the 'Y' shape
    function isY(n, i, j) {

        // For top half: diagonals (i == j or i + j == n - 1)
        // For bottom half: vertical line in center column (j == center)
        return (i <= Math.floor(n / 2) && (i === j || i + j === n - 1)) ||
               (i > Math.floor(n / 2) && j === Math.floor(n / 2));
    }

    // Function to compute the number of operations to convert the grid
    // into one where 'Y' cells have value 'y' and non-Y cells have 'notY'
    function getOperationCount(grid, y, notY) {

        // Get the grid size
        const n = grid.length;

        // Initialize the operation counter
        let operations = 0;

        // Traverse each cell of the grid
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < n; j++) {

                // If the cell is part of Y and doesn't match target Y value
                if (isY(n, i, j)) {
                    if (grid[i][j] !== y) {
                        operations++;
                    }
                } 
                
                // If the cell is outside Y and doesn't match target non-Y value
                else {
                    if (grid[i][j] !== notY) {
                        operations++;
                    }
                }
            }
        }

        // Return total operations needed
        return operations;
    }

    // Try all 6 valid (Y value, non-Y value) combinations using 0, 1, 2
    const option1 = getOperationCount(grid, 0, 1);
    const option2 = getOperationCount(grid, 1, 0);
    const option3 = getOperationCount(grid, 1, 2);
    const option4 = getOperationCount(grid, 2, 1);
    const option5 = getOperationCount(grid, 2, 0);
    const option6 = getOperationCount(grid, 0, 2);

    // Return the minimum operations among all options
    return Math.min(option1, option2, option3, option4, option5, option6);
};

Minimum Operations to Write the Letter Y on a Grid Complexity Analysis

Time Complexity: O(n²)

We have two main parts:

  1. minimumOperationsToWriteY
  2. getOperationCount, which is called 6 times (once for each value-pair permutation)

Inner Workings of getOperationCount

  • Grid size: Let n be the number of rows/columns in the grid (since it's n × n and always odd).
  • Inside getOperationCount:
    • We iterate over every cell of the grid.
    • For each cell (i, j):
      • We call isY(n, i, j), which runs in O(1).
      • Then we perform simple comparisons to increment the count.
  • So each getOperationCount call runs in:O(n²) — since we're visiting every cell once.

Number of Calls to getOperationCount

  • We try all 6 valid (y, notY) combinations from values {0, 1, 2}.
  • So we call getOperationCount 6 times.

Final Time Complexity

Each getOperationCount = O(n²)
Number of calls = 6
So total time = 6 × O(n²) = O(n²)

The constant factor 6 is negligible in Big-O, so overall:

Time Complexity: O(n²)

Space Complexity: O(n²)

  1. Auxiliary Space Complexity: O(1)
    The extra space used in the algorithm includes only a few primitive variables, such as:
    Loop counters like i, j
    Integer variables like operations, n, and the (y, notY) values
    Therefore, the auxiliary space complexity is O(1).
  2. Total Space Complexity: O(n²)
    The algorithm works on a given n × n input grid, which is provided to us. We do not create any temporary grid or additional 2D structure.
    Since we only read from the input grid and do not allocate new space proportional to n², the space we use is essentially the space taken by the input itself.

    Therefore, the total space complexity is O(n²) due to the input grid size, but no extra grid is created..

Will Brute Force Work Against the Given Constraints? 

For the current solution, the time complexity is O(n × n) = O(n²), where:
n is the number of rows (and columns) in the square grid.

In the worst-case scenario:

  • n = 49, so the number of cells is 49 × 49 = 2401
  • We process all cells 6 times, so total operations = 6 × 2401 = 14,406

Even though this is a brute-force solution, the absolute number of operations — under 15,000 in the worst case — is very efficient and well within the typical limits accepted by online judges like LeetCode, which usually allow up to 1,000,000 (10⁶) operations per test case.

Can there be any other approach?

We’re given a square grid where each cell contains a number — either 0, 1, or 2. Our job is to "draw" the shape of the letter Y on this grid, but not visually — instead, by making sure:

  1. All the cells belonging to the Y have one common value (say all are 0s).
  2. All the remaining cells (non-Y) also have a different single value (say all are 1s).
  3. The Y cells and non-Y cells must not share the same value.

And we want to do this using the minimum number of changes — meaning we want to touch as few grid cells as possible.

An operation is changing a cell’s value. So we want to change only those cells that are not already what we want them to be.

Let’s say you decide that:

  • The value for all Y cells should be 0, and
  • The value for all non-Y cells should be 1.

Then all you have to do is look at every cell, and:

  • If it belongs to Y but isn’t already 0, you’ll count 1 operation.
  • If it doesn't belong to Y but isn’t already 1, that’s another operation.

So, in total, you're just counting mismatches — how many cells you need to fix to get this nice "Y-pattern" with two consistent values.

Now, remember: we only have 3 possible values in the grid — 0, 1, or 2.

This means, for the Y cells, we can try all three options (0, 1, 2) as their target value.

And for the non-Y cells, we can also try all three values.

But since Y and non-Y need to have different values, that leaves us with 6 combinations (like Y = 0 and non-Y = 1, Y = 2 and non-Y = 0, etc.).

Rather than repeating work, we just need to count how many times each value appears in the Y cells and the non-Y cells. That way, we don’t have to check every cell repeatedly for every combination.

Minimum Operations to Write the Letter Y on a Grid Algorithm

Here’s where we introduce a frequency table (basically a hash table or array) to keep track of how many 0s, 1s, and 2s are in the Y and non-Y regions.

So, we build two arrays:

  • One for the Y part of the grid, say yFreq[3]
  • One for the non-Y part, say nonYFreq[3]

As we scan through the grid:

  • If a cell is part of the Y shape, we do yFreq[value]++
  • Otherwise, we do nonYFreq[value]++

We also keep track of total number of Y cells and non-Y cells, so we know how many should match the target value.

Once we have all the frequencies, we can now simulate all 6 valid combinations of (Y value, non-Y value), and for each pair:

  • Y-modify cost = number of Y cells - how many already match the target Y value
  • non-Y modify cost = number of non-Y cells - how many already match the target non-Y value

We add those two costs, and track the minimum across all pairs.

So in effect, we’ve reduced a potentially expensive process into a very fast one by just counting — and only scanning the grid once.

Let us understand this with a video,

0:00
/1:35

Minimum Operations to Write the Letter Y on a Grid-Optimal-Approach-Animation

Let's understand with an example:

Minimum Operations to Write the Letter Y on a Grid Example:

Input:

grid = [[1, 2, 2]
[1, 1, 0]
[0, 1, 0]]

Step 1: Identify Y and non-Y positions (n = 3, center = 1)

Y-cells (forming a 'Y'):

  • Top arms: (0,0), (0,2)
  • Middle vertical stem: (1,1)
  • Bottom stem: (2,1)

→ Y positions: (0,0), (0,2), (1,1), (2,1) → values: [1, 2, 1, 1]

non-Y cells:

  • (0,1), (1,0), (1,2), (2,0), (2,2) → values: [2,1,0,0,0]

Step 2: Frequency count

Y frequencies:

  • 0 → 0
  • 1 → 3
  • 2 → 1

non-Y frequencies:

  • 0 → 3
  • 1 → 1
  • 2 → 1

Step 3: Try all valid (Y, non-Y) combinations (where values ≠)

Let’s try all 6:

  1. Y = 0, non-Y = 1
    Y changes = 4 - 0 = 4
    non-Y changes = 5 - 1 = 4
    → total = 8
  2. Y = 0, non-Y = 2
    Y changes = 4 - 0 = 4
    non-Y changes = 5 - 1 = 4
    → total = 8
  3. Y = 1, non-Y = 0
    Y changes = 4 - 3 = 1
    non-Y changes = 5 - 3 = 2
    → total = 3
  4. Y = 1, non-Y = 2
    Y changes = 4 - 3 = 1
    non-Y changes = 5 - 1 = 4
    → total = 5
  5. Y = 2, non-Y = 0
    Y changes = 4 - 1 = 3
    non-Y changes = 5 - 3 = 2
    → total = 5
  6. Y = 2, non-Y = 1
    Y changes = 4 - 1 = 3
    non-Y changes = 5 - 1 = 4
    → total = 7

Final Result: Minimum operations = 3 (Y = 1, non-Y = 0)

How to code it up:

  1. Initialize variables
    • Get n = grid.length and center = n / 2.
    • Create two frequency arrays of size 3: yFreq and nonYFreq.
    • Initialize counters totalY and totalNonY to 0.
  2. Classify cells as Y or non-Y
    • Loop through each cell (i, j) in the grid.
    • If the cell lies on the Y-shape (using conditions for diagonals and vertical center stem), update yFreq[grid[i][j]] and increment totalY.
    • Otherwise, update nonYFreq[grid[i][j]] and increment totalNonY.
  3. Try all valid value combinations
    • Loop through values y and nonY from 0 to 2.
    • Skip if y == nonY (they must differ).
    • Compute:
      • yChanges = totalY - yFreq[y]
      • nonYChanges = totalNonY - nonYFreq[nonY]
      • Update minOperations with the minimum of current and total changes.
  4. Return the minimum operations found.

Minimum Operations to Write the Letter Y on a Grid Solution

Code Implementation / Leetcode solution of Minimum Operations to Write the Letter Y on a Grid
1. Minimum Operations to Write the Letter Y on a Grid solution in C++ Try on Compiler
class Solution {
    // Function to check if a cell is part of the Y shape
    bool isY(int n, int i, int j)
    {
        return (i <= n/2 && (i == j || i + j == n - 1)) || (i > n/2 && j == n/2);
    }

public:
    int minimumOperationsToWriteY(vector<vector<int>>& grid) {
        // Get the size of the grid
        int n = grid.size();

        // Frequency count for values on the Y-shape
        vector<int> yFreq(3, 0);

        // Frequency count for values outside the Y-shape
        vector<int> nonYFreq(3, 0);
        
        // Total number of cells in Y-shape
        int totalY = 0;

        // Total number of cells not in Y-shape
        int totalNonY = 0;

        // Iterate over all cells in the grid
        for (int i = 0; i < n; ++i) 
        {
            for (int j = 0; j < n; ++j) 
            {
                // If the cell is part of the Y
                if (isY(n, i, j)) 
                {
                    // Count frequency of the value in Y
                    yFreq[grid[i][j]]++;

                    // Increment Y cell count
                    totalY++;
                } 
                else 
                {
                    // Count frequency of the value outside Y
                    nonYFreq[grid[i][j]]++;

                    // Increment non-Y cell count
                    totalNonY++;
                }
            }
        }

        // Initialize minimum operations to a large number
        int minOp = INT_MAX;

        // Try all possible pairs (y, nonY) from values 0, 1, 2
        for (int y = 0; y < 3; ++y) {
            for (int nonY = 0; nonY < 3; ++nonY) {

                // Skip if values are the same
                if (y == nonY) 
                    continue;

                // Operations to convert Y area to value y
                int yModifyCost = totalY - yFreq[y];

                // Operations to convert non-Y area to value nonY
                int nonYModifyCost = totalNonY - nonYFreq[nonY];

                // Update minimum operations
                minOp = min(minOp, yModifyCost + nonYModifyCost);
            }
        }

        // Return final answer
        return minOp;
    }
};

2. Minimum Operations to Write the Letter Y on a Grid solution in Java Try on Compiler
class Solution {
    // Function to check if a cell is part of the Y shape
    private boolean isY(int n, int i, int j) {
        return (i <= n / 2 && (i == j || i + j == n - 1)) || (i > n / 2 && j == n / 2);
    }

    public int minimumOperationsToWriteY(int[][] grid) {
        // Grid size
        int n = grid.length;

        // Frequency counters for Y cells
        int[] yFreq = new int[3];

        // Frequency counters for non-Y cells
        int[] nonYFreq = new int[3];

        // Count of Y cells
        int totalY = 0;

        // Count of non-Y cells
        int totalNonY = 0;

        // Loop through the grid
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                // Check if current cell is in Y
                if (isY(n, i, j)) {
                    yFreq[grid[i][j]]++;
                    totalY++;
                } else {
                    nonYFreq[grid[i][j]]++;
                    totalNonY++;
                }
            }
        }

        // Initialize minimum operations
        int minOp = Integer.MAX_VALUE;

        // Try all combinations of Y and non-Y values
        for (int y = 0; y < 3; ++y) {
            for (int nonY = 0; nonY < 3; ++nonY) {
                if (y == nonY)
                    continue;

                int yModify = totalY - yFreq[y];
                int nonYModify = totalNonY - nonYFreq[nonY];
                minOp = Math.min(minOp, yModify + nonYModify);
            }
        }

        // Return the minimum operations
        return minOp;
    }
}

3. Minimum Operations to Write the Letter Y on a Grid solution in Python Try on Compiler
class Solution:
    def isY(self, n, i, j):
        # Check if the cell belongs to the Y shape
        return (i <= n // 2 and (i == j or i + j == n - 1)) or (i > n // 2 and j == n // 2)

    def minimumOperationsToWriteY(self, grid):
        # Get grid size
        n = len(grid)

        # Frequency counters for Y and non-Y
        yFreq = [0] * 3
        nonYFreq = [0] * 3

        # Count of Y and non-Y cells
        totalY = 0
        totalNonY = 0

        # Traverse the grid
        for i in range(n):
            for j in range(n):
                if self.isY(n, i, j):
                    yFreq[grid[i][j]] += 1
                    totalY += 1
                else:
                    nonYFreq[grid[i][j]] += 1
                    totalNonY += 1

        # Initialize the minimum operations
        minOp = float('inf')

        # Try all combinations of Y and non-Y values
        for y in range(3):
            for nonY in range(3):
                if y == nonY:
                    continue
                yModify = totalY - yFreq[y]
                nonYModify = totalNonY - nonYFreq[nonY]
                minOp = min(minOp, yModify + nonYModify)

        # Return the result
        return minOp

4. Minimum Operations to Write the Letter Y on a Grid solution in Javascript Try on Compiler
var minimumOperationsToWriteY = function(grid) {
    // Get the grid size
    const n = grid.length;

    // Frequency counters for Y and non-Y cells
    const yFreq = [0, 0, 0];
    const nonYFreq = [0, 0, 0];

    // Count of Y and non-Y cells
    let totalY = 0;
    let totalNonY = 0;

    // Helper function to check if cell is in Y
    const isY = (n, i, j) => {
        return (i <= Math.floor(n / 2) && (i === j || i + j === n - 1)) || (i > Math.floor(n / 2) && j === Math.floor(n / 2));
    };

    // Traverse the grid
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            if (isY(n, i, j)) {
                yFreq[grid[i][j]]++;
                totalY++;
            } else {
                nonYFreq[grid[i][j]]++;
                totalNonY++;
            }
        }
    }

    // Initialize minimum operations
    let minOp = Infinity;

    // Try all combinations of Y and non-Y values
    for (let y = 0; y < 3; y++) {
        for (let nonY = 0; nonY < 3; nonY++) {
            if (y === nonY) continue;

            let yModify = totalY - yFreq[y];
            let nonYModify = totalNonY - nonYFreq[nonY];
            minOp = Math.min(minOp, yModify + nonYModify);
        }
    }

    // Return final answer
    return minOp;
};

Minimum Operations to Write the Letter Y on a Grid Complexity Analysis

Time Complexity: O(n²)

Let’s walk through it step-by-step:

1. Scanning the Grid: O(n²)

  • The grid has n rows and n columns.
  • We visit each cell exactly once in a nested loop.
  • For each cell:
    • We check whether it belongs to the Y-shaped region.
    • Then, based on that, we increment the frequency count in either the Y region or the non-Y region.
  • So this part takes O(n²) time in total.

2. Trying All Value Combinations: O(1)

  • We try every possible combination of values (0, 1, 2) for the Y and non-Y regions.
  • There are 3 × 3 = 9 combinations in total.
  • But we skip the ones where both regions have the same value, leaving us with 6 valid combinations.
  • For each, we calculate how many modifications are needed and track the minimum.
  • Since this part only runs a fixed number of times, it takes O(1) time.

Total Time Complexity: O(n²)

Space Complexity: O(n²)

  1. Auxiliary Space Complexity: O(1)
    We use two fixed-size frequency arrays of size 3 each (yFreq and nonYFreq) to count occurrences of values 0, 1, 2 in the Y and non-Y parts of the grid.
    This result grid takes O(1) space.
  2. Total Space Complexity: O(n²)
    The input grid is a 2D matrix of size n × n, and it's given as part of the problem input.
    So, the total space complexity is O(n²) due to the input grid.

Similar Problems

When solving problems involving a matrix, we often break it down into smaller parts or convert it into an array for easier processing. In many cases, counting specific values—like how many times an element appears—becomes important, especially when comparing rows or columns. To make this faster and more efficient, we can use a hash table, which allows quick access to frequency data. Together, these tools form a solid foundation for tackling a wide range of logic-based problems.

Now that we have successfully tackled this problem, let's try similar problems.

Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.

A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).

Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

Element at grid[i][j] moves to grid[i][j + 1].

Element at grid[i][n - 1] moves to grid[i + 1][0].

Element at grid[m - 1][n - 1] moves to grid[0][0].

Return the 2D grid after applying shift operation k times.

💡
Showcase your skills by joining LearnYard Technologies FZ-LLC as a Technical Content Writer. Apply now and inspire the next generation of learners—fill out the form: https://forms.gle/CGDsbGkcapSfvXKM8