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

Imagine you have a square grid of cells where each cell contains one of three values: 0, 1, or 2. Your mission is to transform this grid so that it displays a perfect Letter Y pattern!

The Letter Y consists of three parts:

  • ๐Ÿ”ธ Left diagonal: from top-left corner to the center
  • ๐Ÿ”ธ Right diagonal: from top-right corner to the center
  • ๐Ÿ”ธ Vertical line: from center to the bottom edge

For the grid to display a valid Letter Y, you need:

  1. All cells belonging to the Y must have the same value
  2. All cells NOT belonging to the Y must have the same value
  3. The Y cells and non-Y cells must have different values

In one operation, you can change any cell to any value (0, 1, or 2). Find the minimum operations needed to create a perfect Letter Y!

Input & Output

example_1.py โ€” Basic 3x3 Grid
$ Input: grid = [[1,2,2],[1,1,0],[0,1,0]]
โ€บ Output: 3
๐Ÿ’ก Note: We can change grid[0][1] to 1, grid[1][2] to 1, and grid[2][2] to 1. The Y pattern will have value 1, and the background will have value 0.
example_2.py โ€” All Same Values
$ Input: grid = [[2,1,0],[1,1,1],[0,1,0]]
โ€บ Output: 4
๐Ÿ’ก Note: The center and bottom cells of Y already have value 1. We need to change 2 diagonal cells to 1, and 2 background cells to a different value (like 0).
example_3.py โ€” Larger 5x5 Grid
$ Input: grid = [[0,1,1,1,0],[2,1,0,1,2],[2,2,2,2,2],[2,1,2,1,2],[2,1,2,1,2]]
โ€บ Output: 12
๐Ÿ’ก Note: The Y pattern consists of 9 cells total. We need to find the optimal assignment that minimizes total changes across all 25 cells.

Constraints

  • n == grid.length == grid[r].length
  • 3 โ‰ค n โ‰ค 49
  • n is odd
  • 0 โ‰ค grid[r][c] โ‰ค 2

Visualization

Tap to expand
Letter Y Formation ProcessPerfect Y PatternY-cells: 5 totalBackground: 4 totalCount frequenciesFind optimal colors3Min OperationsKey: Red = Y pattern, Gray = Background
Understanding the Visualization
1
Identify Y Pattern
Mark the diagonal lines and vertical stem of the Y
2
Count Current Colors
Analyze what colors are currently in Y vs background
3
Find Best Assignment
Choose colors that minimize tile replacements
4
Calculate Operations
Count how many tiles need to be changed
Key Takeaway
๐ŸŽฏ Key Insight: With only 3 possible values, we can efficiently try all valid color combinations and choose the one requiring minimum changes by counting frequencies rather than explicitly trying each combination.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~15 min Avg. Time
847 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