Magicsheet logo

Minimum Operations to Write the Letter Y on a Grid

Medium
81.6%
Updated 6/1/2025

Minimum Operations to Write the Letter Y on a Grid

What is this problem about?

In the Minimum Operations to Write the Letter Y on a Grid problem, you are given an odd-sized n×n grid filled with values 0, 1, or 2. You need to make all cells that form the letter "Y" hold one value, and all other cells hold a different value — with the minimum number of cell-value changes. The letter Y spans the two diagonal arms from the top corners meeting at the center, then a vertical arm going down. This Minimum Operations to Write the Letter Y on a Grid interview question blends array traversal with counting techniques.

Why is this asked in interviews?

Companies like Uber, Amazon, TikTok, and Capital One ask this question to test grid traversal, careful index computation, and combinatorial enumeration. It checks whether candidates can correctly identify cells belonging to a shape within a matrix, and then optimally assign values to minimize total changes. The array, matrix, hash table, and counting interview pattern is well-represented here.

Algorithmic pattern used

The pattern uses counting with hash maps. First, determine which cells belong to the Y-shape and which don't. Then count the frequency of 0, 1, 2 in both groups. To minimize operations, pick the most frequent value for Y-cells, and the most frequent different value for non-Y-cells. Enumerate all valid (valueY, valueNonY) pairs where valueY ≠ valueNonY, and compute the cost for each combination — taking the minimum.

Example explanation

Suppose a 3x3 grid with Y-shape cells being top-left diagonal, top-right diagonal, and center column. Suppose Y-cells have counts: {0: 3, 1: 1, 2: 2} and non-Y-cells have counts: {0: 1, 1: 3, 2: 2}. Best assignment: Y = 0 (cost = 3 changes), non-Y = 1 (cost = 3 changes), total = 6. Try other combos to confirm this is the minimum.

Common mistakes candidates make

  • Incorrectly computing which cells form the Y-shape, especially the diagonal arms.
  • Forgetting that the value assigned to Y-cells and non-Y-cells must be different.
  • Only trying one assignment instead of enumerating all valid (Y-value, non-Y-value) pairs.
  • Off-by-one in identifying the center meeting point for odd-sized grids.

Interview preparation tip

Grid-shape problems require translating a visual description into precise index conditions. Before coding, sketch the Y-shape on paper and derive the row/column equations that define it. Then the rest is counting — a skill you can sharpen by practicing frequency-counting problems. When minimizing operations over multiple choices, always enumerate all valid combinations; greedy shortcuts often miss the optimal here.

Similar Questions