Make a Square with the Same Color - Problem

You are given a 3 × 3 matrix grid 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 × 2 square where all cells are of the same color.

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

Input & Output

Example 1 — Solution Exists
$ Input: grid = [["B","W","B"],["B","W","W"],["W","B","B"]]
Output: true
💡 Note: The top-right 2×2 square is ["W","B"],["W","W"]. We can change grid[0][2] from "B" to "W" to make all cells "W".
Example 2 — Already Has Square
$ Input: grid = [["B","W","B"],["W","B","W"],["B","W","B"]]
Output: false
💡 Note: No 2×2 square can be made uniform with at most 1 change. Each square needs 2 or more changes.
Example 3 — Already Perfect
$ Input: grid = [["B","B","W"],["B","B","W"],["W","W","W"]]
Output: true
💡 Note: The top-left 2×2 square is already all "B": ["B","B"],["B","B"]. No changes needed.

Constraints

  • grid.length == 3
  • grid[i].length == 3
  • grid[i][j] is either 'W' or 'B'

Visualization

Tap to expand
Make a Square with the Same ColorInput: 3×3 GridBWBBWWWBBCheck: Top-Right 2×2BWBBWWWBB[W,B] [W,W] → 1 change!Solution: Change B→WBWWBWWWBB[W,W] [W,W] ✓All Possible 2×2 PositionsPosition (0,0)Top-Left2 changesPosition (0,1)Top-Right1 changePosition (1,0)Bottom-Left2 changesPosition (1,1)Bottom-Right2 changesResult: true (Solution found at top-right position)
Understanding the Visualization
1
Input Grid
3×3 matrix with B and W cells
2
Check 2×2 Squares
Find squares needing ≤1 change
3
Result
Return true if any square can be made uniform
Key Takeaway
🎯 Key Insight: Check all 4 possible 2×2 squares and count minimum changes needed for each
Asked in
Google 15 Meta 12 Amazon 8
12.0K Views
Medium Frequency
~10 min Avg. Time
425 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen