Facebook Pixel

3127. Make a Square with the Same Color

EasyArrayEnumerationMatrix
Leetcode Link

Problem Description

You are given a 2D matrix grid of size 3 x 3 consisting only of characters 'B' and 'W'. Character 'W' represents the white color, and character 'B' represents the black color.

Your task is to change the color of at most one cell so that the matrix has a 2 x 2 square where all cells are of the same color.

Return true if it is possible to create a 2 x 2 square of the same color, otherwise, return false.

Intuition

We aim to determine if we can form a uniform 2 x 2 square by changing the color of at most one cell in the 3 x 3 grid. To achieve this, we consider all possible 2 x 2 sections within the grid. For each section, we count how many cells are black ('B') and how many are white ('W').

If in any 2 x 2 section the number of black cells is not equal to the number of white cells, it implies there is a potential to achieve uniformity by changing the color of one cell. If such a section is found, we can immediately conclude that it is possible to form a 2 x 2 square of the same color, and the solution should return true.

If after checking all possible 2 x 2 sections no feasible section is found, we conclude that forming a uniform square is not possible and return false.

Solution Approach

The solution approach involves a straightforward enumeration of 2 x 2 squares within the given 3 x 3 grid. Here are the steps followed in the implementation:

  1. Iterate Through Possible 2 x 2 Squares:
    We have four possible starting positions for 2 x 2 squares within the 3 x 3 grid. These positions are (0,0), (0,1), (1,0), and (1,1).

  2. Count Cell Colors in Each 2 x 2 Square:
    For each starting position, consider the cells that form the 2 x 2 square. Count how many cells are black ('B') and how many are white ('W'). Use two counters, cnt1 for white cells and cnt2 for black cells.

  3. Check for Feasibility of Uniformity:
    If for any 2 x 2 section the counts of white and black cells are not equal, it indicates that changing one cell's color can result in a uniform 2 x 2 square. If such a section is found, return true.

  4. Return If No Uniform Square is Possible:
    If all possible 2 x 2 squares have equal counts of black and white cells, then forming such a square is impossible, and the function should return false.

The algorithm effectively utilizes nested loops to traverse and evaluate each potential square, ensuring a precise check with minimal operations.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through an example of the solution approach using the grid below:

grid = [
    ['B', 'W', 'B'],
    ['W', 'B', 'W'],
    ['B', 'W', 'B']
]
  1. Identify Possible 2 x 2 Squares:

    The possible starting positions for 2 x 2 squares in the 3 x 3 grid are (0,0), (0,1), (1,0), and (1,1).

  2. Examine Each 2 x 2 Square:

    a. Square starting at (0,0):

    ```
    B W
    W B
    ```
    • Count of 'B': 2
    • Count of 'W': 2
    • Since the counts are equal, uniformity can't be achieved here.

    b. Square starting at (0,1):

    ```
    W B
    B W
    ```
    • Count of 'B': 2
    • Count of 'W': 2
    • Again, the counts are equal, so one color cannot dominate.

    c. Square starting at (1,0):

    ```
    W B
    B W
    ```
    • Count of 'B': 2
    • Count of 'W': 2
    • The counts are equal here as well.

    d. Square starting at (1,1):

    ```
    B W
    W B
    ```
    • Count of 'B': 2
    • Count of 'W': 2
    • The counts are still equal, indicating no potential for uniformity.
  3. Conclusion:

    Since all the examined 2 x 2 squares have equal counts of colors, altering one cell won't create a uniform square. Therefore, the function returns false.

Solution Implementation

1from typing import List
2
3class Solution:
4    def canMakeSquare(self, grid: List[List[str]]) -> bool:
5        # Iterate over the starting points of the 2x2 squares within the grid
6        for row in range(2):
7            for col in range(2):
8                count_white = 0
9                count_black = 0
10                # Check each cell in the current 2x2 square
11                for dx, dy in [(0, 0), (0, 1), (1, 0), (1, 1)]:
12                    x, y = row + dx, col + dy
13                    count_white += grid[x][y] == "W"  # Count occurrences of "W"
14                    count_black += grid[x][y] == "B"  # Count occurrences of "B"
15                # If the counts of "W" and "B" are not equal, a 2x2 square can be created
16                if count_white != count_black:
17                    return True
18        # If all 2x2 squares have equal counts of "W" and "B", return False
19        return False
20
1class Solution {
2    public boolean canMakeSquare(char[][] grid) {
3        // Directions for checking 2x2 subgrids
4        final int[] directions = {0, 0, 1, 1, 0};
5
6        // Iterate through the grid to check each 2x2 subgrid
7        for (int row = 0; row < 2; ++row) {
8            for (int col = 0; col < 2; ++col) {
9                // Count of 'W' characters in current 2x2 square
10                int whiteCount = 0;
11                // Count of 'B' characters in current 2x2 square
12                int blackCount = 0;
13              
14                // Iterate over the four corners of the 2x2 subgrid
15                for (int corner = 0; corner < 4; ++corner) {
16                    int x = row + directions[corner];
17                    int y = col + directions[corner + 1];
18                  
19                    // Count white and black cells
20                    whiteCount += grid[x][y] == 'W' ? 1 : 0;
21                    blackCount += grid[x][y] == 'B' ? 1 : 0;
22                }
23              
24                // If counts of 'W' and 'B' are not equal, a square can be unequal
25                if (whiteCount != blackCount) {
26                    return true;
27                }
28            }
29        }
30        // If all 2x2 subgrids have equal 'W' and 'B', return false
31        return false;
32    }
33}
34
1class Solution {
2public:
3    // Function to determine if there exists a 2x2 square with unequal counts of 'W' and 'B'
4    bool canMakeSquare(vector<vector<char>>& grid) {
5        // Define movement directions for exploring a 2x2 square
6        int dirs[5] = {0, 0, 1, 1, 0};
7      
8        // Iterate over possible starting points for a 2x2 square in a 2x2 grid
9        for (int i = 0; i < 2; ++i) {
10            for (int j = 0; j < 2; ++j) {
11                // Counters to check the number of 'W's and 'B's in the current 2x2 square
12                int countWhite = 0, countBlack = 0;
13
14                // Check each corner of the current 2x2 square
15                for (int k = 0; k < 4; ++k) {
16                    int x = i + dirs[k];   // Next x-coordinate
17                    int y = j + dirs[k + 1]; // Next y-coordinate
18
19                    // Increment the corresponding counters based on the character in the grid
20                    countWhite += (grid[x][y] == 'W');
21                    countBlack += (grid[x][y] == 'B');
22                }
23
24                // If counts of 'W' and 'B' are different, return true
25                if (countWhite != countBlack) {
26                    return true;
27                }
28            }
29        }
30      
31        // Return false if no such 2x2 square exists
32        return false;
33    }
34};
35
1// Function to check if a 2x2 grid can form a square with 'W' and 'B' such that both are equal
2function canMakeSquare(grid: string[][]): boolean {
3    // Directions to traverse a 2x2 square: (0,0), (0,1), (1,1), (1,0)
4    const directions: number[] = [0, 0, 1, 1, 0];
5
6    // Iterate over each possible 2x2 subgrid in a 2x2 main grid
7    for (let i = 0; i < 2; ++i) {
8        for (let j = 0; j < 2; ++j) {
9            // Initialize counters for 'W' and other characters
10            let countW: number = 0;
11            let countB: number = 0;
12
13            // Traverse the 2x2 subgrid
14            for (let k = 0; k < 4; ++k) {
15                const x: number = i + directions[k];
16                const y: number = j + directions[k + 1];
17              
18                // Count occurrences of 'W' and other characters
19                if (grid[x][y] === 'W') {
20                    ++countW;
21                } else {
22                    ++countB;
23                }
24            }
25
26            // Check if 'W' and other characters are not equal
27            if (countW !== countB) {
28                return true;
29            }
30        }
31    }
32
33    // Return false if no suitable square found
34    return false;
35}
36

Time and Space Complexity

The provided code has a time complexity of O(1) and a space complexity of O(1).

  • Time Complexity O(1): The function evaluates a fixed-size grid (2x2 sub-grid check within a 2x2 structure inside the grid), performing a constant number of operations irrespective of the input size. The loops are limited to small, constant sizes with no dependence on a variable input size.

  • Space Complexity O(1): The function uses a constant amount of additional space. Only a fixed number of variables (cnt1, cnt2, x, y, a, b) are declared, independent of the size of the grid.

Learn more about how to find time and space complexity quickly.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

What's the output of running the following function using the following tree as input?

1def serialize(root):
2    res = []
3    def dfs(root):
4        if not root:
5            res.append('x')
6            return
7        res.append(root.val)
8        dfs(root.left)
9        dfs(root.right)
10    dfs(root)
11    return ' '.join(res)
12
1import java.util.StringJoiner;
2
3public static String serialize(Node root) {
4    StringJoiner res = new StringJoiner(" ");
5    serializeDFS(root, res);
6    return res.toString();
7}
8
9private static void serializeDFS(Node root, StringJoiner result) {
10    if (root == null) {
11        result.add("x");
12        return;
13    }
14    result.add(Integer.toString(root.val));
15    serializeDFS(root.left, result);
16    serializeDFS(root.right, result);
17}
18
1function serialize(root) {
2    let res = [];
3    serialize_dfs(root, res);
4    return res.join(" ");
5}
6
7function serialize_dfs(root, res) {
8    if (!root) {
9        res.push("x");
10        return;
11    }
12    res.push(root.val);
13    serialize_dfs(root.left, res);
14    serialize_dfs(root.right, res);
15}
16

Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More