Minimum Operations to Write the Letter Y on a Grid - Problem

You are given a 0-indexed n × 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.

Input & Output

Example 1 — Basic 3x3 Grid
$ Input: grid = [[1,2,2],[1,1,0],[0,1,0]]
Output: 3
💡 Note: Y cells are at positions (0,0), (0,2), (1,1), (2,1). To minimize operations, set Y=1 and non-Y=0. Need to change 3 non-Y cells: (0,1) from 2→0, (1,0) from 1→0, (1,2) from 0→0 (no change), (2,0) from 0→0, (2,2) from 0→0. Actually need to change (0,1) and (1,0) and (1,2), total 3 operations.
Example 2 — Uniform Values
$ Input: grid = [[2,1,0],[1,0,1],[0,1,2]]
Output: 6
💡 Note: Y cells: (0,0)=2, (0,2)=0, (1,1)=0, (2,1)=1. Non-Y cells: (0,1)=1, (1,0)=1, (1,2)=1, (2,0)=0, (2,2)=2. Best assignment requires changing most cells to achieve uniform regions.
Example 3 — Already Optimal
$ Input: grid = [[0,1,0],[1,0,1],[1,0,1]]
Output: 1
💡 Note: Y cells: (0,0)=0, (0,2)=0, (1,1)=0, (2,1)=0. Non-Y: (0,1)=1, (1,0)=1, (1,2)=1, (2,0)=1, (2,2)=1. Y=0, Non-Y=1 is already mostly correct, need only 1 change.

Constraints

  • n == grid.length == grid[i].length
  • 3 ≤ n ≤ 49
  • n is odd
  • grid[i][j] is either 0, 1, or 2

Visualization

Tap to expand
Y Pattern Grid TransformationOriginal Grid122110010Y Pattern IdentificationYNYNYNNYNGreen = Y cells, Blue = Non-Y cellsOptimal Solution101010010Y=1 (orange), Non-Y=0 (red)Minimum Operations: 3Changes needed: (0,1): 2→0, (1,0): 1→0, (1,2): 0→0
Understanding the Visualization
1
Input Grid
3×3 grid with values 0, 1, 2
2
Identify Y
Mark cells forming Y pattern
3
Optimize Assignment
Find best color combo for minimum operations
Key Takeaway
🎯 Key Insight: With only 3 possible values, we can exhaustively try all valid Y vs non-Y color combinations in constant time
Asked in
Google 12 Meta 8 Amazon 6
8.9K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen