Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
You are given a 2D matrix grid of size 3 x 3 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 x 2 square where all cells are of the same color.
Return true if it is possible to create a 2 x 2 square of the same color, otherwise, return false.
Example 1:
Input: grid = [["B","W","B"],["B","W","W"],["B","W","B"]]
Output: true
Explanation:
It can be done by changing the color of the grid[0][2].
Example 2:
Input: grid = [["B","W","B"],["W","B","W"],["B","W","B"]]
Output: false
Explanation:
It cannot be done by changing at most one cell.
Example 3:
Input: grid = [["B","W","B"],["B","W","W"],["B","W","W"]]
Output: true
Explanation:
The grid already contains a 2 x 2 square of the same color.
Constraints:
grid.length == 3grid[i].length == 3grid[i][j] is either 'W' or 'B'.Problem summary: You are given a 2D matrix grid of size 3 x 3 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 x 2 square where all cells are of the same color. Return true if it is possible to create a 2 x 2 square of the same color, otherwise, return false. .grid-container { display: grid; grid-template-columns: 30px 30px 30px; padding: 10px; } .grid-item { background-color: black; border: 1px solid gray; height: 30px; font-size: 30px; text-align: center; } .grid-item-white { background-color: white; }
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[["B","W","B"],["B","W","W"],["B","W","B"]]
[["B","W","B"],["W","B","W"],["B","W","B"]]
[["B","W","B"],["B","W","W"],["B","W","W"]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3127: Make a Square with the Same Color
class Solution {
public boolean canMakeSquare(char[][] grid) {
final int[] dirs = {0, 0, 1, 1, 0};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
int cnt1 = 0, cnt2 = 0;
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
cnt1 += grid[x][y] == 'W' ? 1 : 0;
cnt2 += grid[x][y] == 'B' ? 1 : 0;
}
if (cnt1 != cnt2) {
return true;
}
}
}
return false;
}
}
// Accepted solution for LeetCode #3127: Make a Square with the Same Color
func canMakeSquare(grid [][]byte) bool {
dirs := [5]int{0, 0, 1, 1, 0}
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
cnt1, cnt2 := 0, 0
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if grid[x][y] == 'W' {
cnt1++
} else {
cnt2++
}
}
if cnt1 != cnt2 {
return true
}
}
}
return false
}
# Accepted solution for LeetCode #3127: Make a Square with the Same Color
class Solution:
def canMakeSquare(self, grid: List[List[str]]) -> bool:
for i in range(0, 2):
for j in range(0, 2):
cnt1 = cnt2 = 0
for a, b in pairwise((0, 0, 1, 1, 0)):
x, y = i + a, j + b
cnt1 += grid[x][y] == "W"
cnt2 += grid[x][y] == "B"
if cnt1 != cnt2:
return True
return False
// Accepted solution for LeetCode #3127: Make a Square with the Same Color
/**
* [3127] Make a Square with the Same Color
*/
pub struct Solution {}
// submission codes start here
const DELTA: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 0), (1, 1)];
impl Solution {
pub fn can_make_square(grid: Vec<Vec<char>>) -> bool {
for i in 0..2 {
for j in 0..2 {
let mut white: i32 = 0;
let mut black: i32 = 0;
for (x, y) in DELTA {
match grid[i + x][j + y] {
'B' => black += 1,
'W' => white += 1,
_ => {}
}
}
if white.abs_diff(black) == 2 || white.abs_diff(black) == 4 {
return true;
}
}
}
false
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3127() {}
}
// Accepted solution for LeetCode #3127: Make a Square with the Same Color
function canMakeSquare(grid: string[][]): boolean {
const dirs: number[] = [0, 0, 1, 1, 0];
for (let i = 0; i < 2; ++i) {
for (let j = 0; j < 2; ++j) {
let [cnt1, cnt2] = [0, 0];
for (let k = 0; k < 4; ++k) {
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (grid[x][y] === 'W') {
++cnt1;
} else {
++cnt2;
}
}
if (cnt1 !== cnt2) {
return true;
}
}
}
return false;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.