Problem 3127

Abstract / Summary

Given a grid, determine if there exists a square where all cells inside have the same color.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
8 lines | 369 bytes | submitted May 1, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (60k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Enumeration
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. Definition of a compact counter white that aggregates the white cell count for any 2 × 2 block.
  2. Invocation of white for each of the four relevant block positions.
  3. 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.70 | σ = 1.82

Complexity Analysis

Time: constant
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
18 links | 7 authors | 5 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   May 1, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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