#3127
Make a Square with the Same Color
EasyArrayMatrixEnumerationEnumerationGrid Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of checking each square, we can count the occurrences of 'B' and 'W' in the grid and determine if changing one cell can create a uniform 2x2 square.
⚙️
Algorithm
4 steps- 1Step 1: Count the occurrences of 'B' and 'W' in the entire grid.
- 2Step 2: If there are at least 3 of one color in any 2x2 square, return true.
- 3Step 3: If there are exactly 2 of one color and 2 of the other in any square, return false.
- 4Step 4: If we find a configuration that allows for one change to create a uniform square, return true.
solution.py7 lines
1def canMakeSquare(grid):
2 for i in range(2):
3 for j in range(2):
4 countB = sum(grid[i+x][j+j] == 'B' for x in range(2) for y in range(2))
5 if countB >= 3:
6 return True
7 return Falseℹ
Complexity note: The complexity is O(1) as we are only checking a fixed number of squares (4) in a fixed-size grid (3x3).
- 1Understanding the grid structure helps in identifying possible squares quickly.
- 2Counting occurrences of colors can simplify the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.