Python 3127.py
class Solution:
def canMakeSquare(self, grid: List[List[str]]) -> bool:
def white(x, y):
return (grid[y ][x] == "W") + (grid[y ][x + 1] == "W") + \
(grid[y + 1][x] == "W") + (grid[y + 1][x + 1] == "W")
return white(0, 0) != 2 or white(0, 1) != 2 or \
white(1, 0) != 2 or white(1, 1) != 2
Difficulty
and has an acceptance rate of about 53% (60k+ submissions).
Typical patterns to solve this problem:
- Array
- Enumeration
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a single method canMakeSquare that determines whether a 2 × 2 sub-grid of a larger binary color grid can be transformed into a uniform square. The grid consists of characters "W" (white) and "B" (black). The method evaluates four overlapping 2 × 2 windows that cover the top-left corner of the input and returns a Boolean indicating if at least one of those windows does not contain exactly two white cells.
Core Logic
The method defines a nested helper function white(x, y) that counts how many of the four cells in the 2 × 2 block starting at column x and row y are white. The count is obtained by evaluating each cell’s equality with "W" and summing the Boolean results, which Python treats as integers (True → 1, False → 0).
def white(x, y):
return (grid[y ][x] == "W") + (grid[y ][x + 1] == "W") + \
(grid[y + 1][x] == "W") + (grid[y + 1][x + 1] == "W")
After defining the helper, the method calls white for the four possible 2 × 2 positions that intersect the top-left 3 × 3 region of the grid:
- top-left block at (0, 0)
- block shifted right by one column at (0, 1)
- block shifted down by one row at (1, 0)
- block shifted both right and down at (1, 1)
The return expression uses logical OR to combine the four checks:
return white(0, 0) != 2 or white(0, 1) != 2 or \
white(1, 0) != 2 or white(1, 1) != 2
If any of the four windows has a white count different from two, the method returns True; otherwise it returns False.
Edge Cases Handled
The implementation implicitly handles several boundary conditions:
When the grid is exactly 2 × 2, the four calls to white all reference the same single block. The logical OR still works because each call evaluates the same count, and the result correctly reflects whether that block deviates from the “exactly two white cells” condition.
If the grid is larger than 3 × 3, only the four windows that intersect the top-left 3 × 3 area are examined. This matches the problem’s requirement to consider only those positions, avoiding out-of-range indexing.
The Boolean arithmetic in white safely deals with any mixture of "W" and "B" characters, because each comparison yields a Boolean that contributes either 0 or 1 to the sum.
Performance Characteristics
The helper white performs a constant amount of work: four direct index accesses and four equality checks. Because the method invokes white exactly four times, the total number of operations scales with a fixed constant, independent of the overall size of grid. This yields a highly predictable execution time.
The use of short-circuit evaluation in the combined OR expression provides a minor optimization: as soon as a window with a non-two white count is found, the remaining white calls are skipped, potentially reducing the number of cell accesses in favorable inputs.
The code avoids any explicit loops, recursion, or auxiliary data structures, thereby minimizing overhead and memory usage. The direct indexing approach ensures cache-friendly access patterns for the examined cells.
Summary of Key Steps
The method’s workflow can be broken down into three conceptual stages:
- Definition of a compact counter
whitethat aggregates the white cell count for any 2 × 2 block. - Invocation of
whitefor each of the four relevant block positions. - Immediate Boolean combination of the results to decide the final answer.
Each stage is expressed concisely, leveraging Python’s ability to treat Boolean values as integers and to short-circuit logical operators. This results in a clear, efficient solution that directly addresses the problem’s constraints.
ELI5 - Simplified Explanation
Imagine a big board made of little squares that are colored either white or black. Think of the board like a small grid with three rows and three columns. This puzzle is looking for a tiny group of four squares that form a square shape. Inside that small square layout, there are four spots. The code checks every possible two-by-two square on the board to see if three or more of the spots are the same color. If any of these small groups have three or four white squares, or three or four black squares, the mission is complete. The math inside the little helper part simply counts how many white squares are in a tiny group. If that count is zero, one, three, or four, it means the group is mostly one color. If the count is two, it means there is an even mix of colors, which is not what is wanted. The code keeps looking at different spots until it finds one that is not an even mix.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | Java | C++ | Python | TS | |
| WalkCCC | Java | C++ | Python | |||
| leetcode.ca | Java | C++ | Go | Python | TS | |
| Progiez | Java | C++ | Python | |||
| github | charles-wangkai | Java | ||||
| fsq | C++ | |||||
| varunu28 | Java | |||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | C++, Python, Java | |||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||
| Progiez | C++, Java, Python | |||||
| charles-wangkai | Java | |||||
| fsq | C++ | |||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 3069: Distribute Elements Into Two Arrays I
- problem 3074: Apple Redistribution into Boxes
- problem 3083: Existence of a Substring in a String and Its Reverse
- problem 3114: Latest Time You Can Obtain After Replacing Characters
- problem 2513: Minimize the Maximum of Two Arrays
- problem 3070: Count Submatrices with Top-Left Element and Sum Less Than k
- problem 3112: Minimum Time to Visit Disappearing Nodes
- problem 3128: Right Triangles
- problem 2503: Maximum Number of Points From Grid Queries
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality