#3071

Minimum Operations to Write the Letter Y on a Grid

Medium
ArrayHash TableMatrixCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the structure of the grid and the properties of the letter Y to minimize operations by directly calculating the necessary changes based on counts of values in Y and non-Y cells.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count occurrences of each value (0, 1, 2) in both Y and non-Y cells.
  2. 2Step 2: Determine the maximum frequency of values in Y and non-Y cells.
  3. 3Step 3: Calculate the number of operations needed by subtracting the maximum frequency from the total count of Y and non-Y cells.
solution.py22 lines
1# Full working Python code
2
3def min_operations_optimal(grid):
4    n = len(grid)
5    y_count = [0, 0, 0]
6    non_y_count = [0, 0, 0]
7    center = n // 2
8
9    for r in range(n):
10        for c in range(n):
11            if r == c or r + c == n - 1 or c == center:
12                y_count[grid[r][c]] += 1
13            else:
14                non_y_count[grid[r][c]] += 1
15
16    y_operations = len(y_count) - max(y_count)
17    non_y_operations = len(non_y_count) - max(non_y_count)
18
19    return y_operations + non_y_operations
20
21# Example usage
22print(min_operations_optimal([[1,2,2],[1,1,0],[0,1,0]]))  # Output: 3

Complexity note: The time complexity is O(n) because we only need to traverse the grid once to count the occurrences of each value in Y and non-Y cells. The space complexity is O(1) since we use a fixed-size array to store counts.

  • 1The grid's structure allows for a clear separation of Y and non-Y cells.
  • 2Counting occurrences efficiently helps minimize operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.