Analysis: multiple for-loops still in constant time

This is an interesting problem: the key here is to keep track of the frequency within the Y, frequency outside of the Y, and then at this point we can try "all possibilities". But all possibilities here means actually a constant time. In the code below, you have 3*3*3 = 27 iterations. Just be careful when you see nested loops, they may still be cnstant time. Code is down below, cheers, ACC.

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

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

Example 1:

Input: grid = [[1,2,2],[1,1,0],[0,1,0]]
Output: 3
Explanation: We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.

Example 2:

Input: grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
Output: 12
Explanation: We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. 
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.

Constraints:

  • 3 <= n <= 49
  • n == grid.length == grid[i].length
  • 0 <= grid[i][j] <= 2
  • n is odd.

 public int MinimumOperationsToWriteY(int[][] grid)
 {
 Hashtable freqInY = new Hashtable();
 Hashtable freqOutY = new Hashtable();
 FrequencyCountInY(grid, freqInY);
 FrequencyCountOutY(grid, freqOutY);
 int retVal = Int32.MaxValue;
 for (int inY = 0; inY <= 2; inY++)
 {
 for (int outY = 0; outY <= 2; outY++)
 {
 if (inY != outY)
 {
 retVal = Math.Min(retVal, NumberOperationsInYOutY(freqInY, freqOutY, inY, outY));
 }
 }
 }
 return retVal;
 }
 private int NumberOperationsInYOutY(Hashtable freqInY, Hashtable freqOutY, int inY, int outY)
 {
 int numberInY = 0;
 foreach (int key in freqInY.Keys)
 {
 if (key != inY)
 {
 numberInY += (int)freqInY[key];
 }
 }
 int numberOutY = 0;
 foreach (int key in freqOutY.Keys)
 {
 if (key != outY)
 {
 numberOutY += (int)freqOutY[key];
 }
 }
 return numberInY + numberOutY;
 }
 private void FrequencyCountOutY(int[][] grid, Hashtable frequency)
 {
 for (int r = 0; r < grid.Length; r++)
 {
 for (int c = 0; c < grid[r].Length; c++)
 {
 if (grid[r][c] != -1)
 {
 if (!frequency.ContainsKey(grid[r][c])) frequency.Add(grid[r][c], 0);
 frequency[grid[r][c]] = (int)frequency[grid[r][c]] + 1;
 }
 }
 }
 }
 private void FrequencyCountInY(int[][] grid, Hashtable frequency)
 {
 int colLeft = 0;
 int colRight = grid[0].Length - 1;
 int row = 0;
 //Diagonals
 while (row < grid.Length / 2)
 {
 int[] numbers = { grid[row][colLeft], grid[row][colRight] };
 foreach (int n in numbers)
 {
 if (!frequency.ContainsKey(n)) frequency.Add(n, 0);
 frequency[n] = (int)frequency[n] + 1;
 }
 grid[row][colLeft] = -1;
 grid[row][colRight] = -1;
 colLeft++;
 colRight--;
 row++;
 }
 //Center
 for (int r = grid.Length / 2; r < grid.Length; r++)
 {
 int[] numbers = { grid[r][grid[r].Length / 2] };
 foreach (int n in numbers)
 {
 if (!frequency.ContainsKey(n)) frequency.Add(n, 0);
 frequency[n] = (int)frequency[n] + 1;
 }
 grid[r][grid[r].Length / 2] = -1;
 }
 }

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...