Make a Square with the Same Color Problem
#3127
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3127.
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.
Example 1:
Input: grid = [["B","W","B"],["B","W","W"],["B","W","B"]]
Output: true
Explanation:
It can be done by changing the color of the grid[0][2].
Example 2:
Input: grid = [["B","W","B"],["W","B","W"],["B","W","B"]]
Output: false
Explanation:
It cannot be done by changing at most one cell.
Example 3:
Input: grid = [["B","W","B"],["B","W","W"],["B","W","W"]]
Output: true
Explanation:
The grid already contains a 2 x 2 square of the same color.
Constraints:
grid.length == 3grid[i].length == 3grid[i][j]is either'W'or'B'.
Solution
Approach: Enumeration
There are only four 2 x 2 squares. For each, count the white and black cells. If the counts differ (3 and 1, or 4 and 0), one flip, or none, makes it uniform, so return true. If every square has two of each, return false.
Complexity: O(1) time and O(1) space.
class Solution:
def canMakeSquare(self, grid: List[List[str]]) -> bool:
dirs = (0, 0, 1, 1, 0)
for i in range(0, 2):
for j in range(0, 2):
cnt1 = cnt2 = 0
for k in range(4):
x, y = i + dirs[k], j + dirs[k + 1]
cnt1 += grid[x][y] == "W"
cnt2 += grid[x][y] == "B"
if cnt1 != cnt2:
return True
return False