#3071
Medium Algorithms Minimum operations to write the letter y on a grid
Array Hash Table Matrix Counting
64.3% acceptance
Feb 25, 2026
147
34
You are given a 0-indexed n x n grid where n is odd, and grid[r][c] is 0, 1, or 2.
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.
The diagonal starting at the top-right cell and ending at the center cell.
The vertical line starting at the center cell and ending at the bottom border.
Return the minimum number of operations needed to write the letter Y on the grid.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn minimum_operations_to_write_y(grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
let mid = n / 2;
let mut y_freq = [0i32; 3];
let mut rest_freq = [0i32; 3];
for r in 0..n {
for c in 0..n {
let in_y = (r <= mid && (c == r || c == n - 1 - r)) || (r >= mid && c == mid);
if in_y { y_freq[grid[r][c] as usize] += 1; }
else { rest_freq[grid[r][c] as usize] += 1; }
}
}
let total_y: i32 = y_freq.iter().sum();
let total_rest: i32 = rest_freq.iter().sum();
let mut ans = i32::MAX;
for y_val in 0..3 {
for r_val in 0..3 {
if y_val != r_val {
let cost = (total_y - y_freq[y_val]) + (total_rest - rest_freq[r_val]);
ans = ans.min(cost);
}
}
}
ans
}
}