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 Color INPUT 3x3 Grid Matrix B W B B W W W B B Input Values grid = [ ["B","W","B"], ["B","W","W"], ["W","B","B"] ] ALGORITHM STEPS 1 Check 2x2 Squares Iterate all four possible 2x2 squares in 3x3 grid 2 Count Colors For each 2x2 square, count B and W cells 3 Early Termination If 3+ same color found, return true immediately 4 Final Check Return false if no valid square exists Top-left 2x2: B=2 W=2 FINAL RESULT Bottom-right 2x2 square has 3 same color cells! B W B B W W W B B Change W to B at (1,1) to get all B square! Output true OK Key Insight: Early Termination Check - In a 3x3 grid, there are only 4 possible 2x2 squares to examine. For any 2x2 square, if at least 3 cells share the same color, we can change at most 1 cell to make all 4 cells uniform. Time Complexity: O(1) since grid size is fixed. TutorialsPoint - Make a Square with the Same Color | Early Termination Check Approach
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