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.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an m x n binary matrix matrix.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).
Return the maximum number of rows that have all values equal after some number of flips.
Example 1:
Input: matrix = [[0,1],[1,1]] Output: 1 Explanation: After flipping no values, 1 row has all values equal.
Example 2:
Input: matrix = [[0,1],[1,0]] Output: 2 Explanation: After flipping values in the first column, both rows have equal values.
Example 3:
Input: matrix = [[0,0,0],[0,0,1],[1,1,0]] Output: 2 Explanation: After flipping values in the first two columns, the last two rows have equal values.
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 300matrix[i][j] is either 0 or 1.Problem summary: You are given an m x n binary matrix matrix. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa). Return the maximum number of rows that have all values equal after some number of flips.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[[0,1],[1,1]]
[[0,1],[1,0]]
[[0,0,0],[0,0,1],[1,1,0]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1072: Flip Columns For Maximum Number of Equal Rows
class Solution {
public int maxEqualRowsAfterFlips(int[][] matrix) {
Map<String, Integer> cnt = new HashMap<>();
int ans = 0, n = matrix[0].length;
for (var row : matrix) {
char[] cs = new char[n];
for (int i = 0; i < n; ++i) {
cs[i] = (char) (row[0] ^ row[i]);
}
ans = Math.max(ans, cnt.merge(String.valueOf(cs), 1, Integer::sum));
}
return ans;
}
}
// Accepted solution for LeetCode #1072: Flip Columns For Maximum Number of Equal Rows
func maxEqualRowsAfterFlips(matrix [][]int) (ans int) {
cnt := map[string]int{}
for _, row := range matrix {
s := []byte{}
for _, x := range row {
if row[0] == 1 {
x ^= 1
}
s = append(s, byte(x)+'0')
}
t := string(s)
cnt[t]++
ans = max(ans, cnt[t])
}
return
}
# Accepted solution for LeetCode #1072: Flip Columns For Maximum Number of Equal Rows
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
cnt = Counter()
for row in matrix:
t = tuple(row) if row[0] == 0 else tuple(x ^ 1 for x in row)
cnt[t] += 1
return max(cnt.values())
// Accepted solution for LeetCode #1072: Flip Columns For Maximum Number of Equal Rows
struct Solution;
impl Solution {
fn max_equal_rows_after_flips(matrix: Vec<Vec<i32>>) -> i32 {
let n = matrix.len();
let m = matrix[0].len();
let mut res = vec![1; n];
for i in 0..n {
for j in 0..i {
let count: usize = matrix[i]
.iter()
.zip(matrix[j].iter())
.map(|(x, y)| if x == y { 1 } else { 0 })
.sum();
if count == 0 || count == m {
res[i] += 1;
res[j] += 1;
}
}
}
*res.iter().max().unwrap() as i32
}
}
#[test]
fn test() {
let matrix = vec_vec_i32![[0, 1], [1, 1]];
let res = 1;
assert_eq!(Solution::max_equal_rows_after_flips(matrix), res);
let matrix = vec_vec_i32![[0, 1], [1, 0]];
let res = 2;
assert_eq!(Solution::max_equal_rows_after_flips(matrix), res);
let matrix = vec_vec_i32![[0, 0, 0], [0, 0, 1], [1, 1, 0]];
let res = 2;
assert_eq!(Solution::max_equal_rows_after_flips(matrix), res);
}
// Accepted solution for LeetCode #1072: Flip Columns For Maximum Number of Equal Rows
function maxEqualRowsAfterFlips(matrix: number[][]): number {
const cnt = new Map<string, number>();
let ans = 0;
for (const row of matrix) {
if (row[0] === 1) {
for (let i = 0; i < row.length; i++) {
row[i] ^= 1;
}
}
const s = row.join('');
cnt.set(s, (cnt.get(s) || 0) + 1);
ans = Math.max(ans, cnt.get(s)!);
}
return ans;
}
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.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.