Flip Columns For Maximum Number of Equal Rows

medium hash map matrix counting

Problem

You are given an m x n binary matrix. You may choose any number of columns and flip every cell in those columns (turning 0 into 1 and 1 into 0). Return the maximum number of rows that can be made to have all values equal after some sequence of flips.

Inputmatrix = [[0,0,0],[0,0,1],[1,1,0]]
Output2
Flip no columns: rows [0,0,0] and [1,1,0] are not yet equal. But two rows share the same flip pattern — see below — so 2 rows can become all-equal at once.

def max_equal_rows_after_flips(matrix):
    count = {}
    best = 0
    for row in matrix:
        first = row[0]
        key = tuple(c ^ first for c in row)
        count[key] = count.get(key, 0) + 1
        best = max(best, count[key])
    return best
function maxEqualRowsAfterFlips(matrix) {
  const count = new Map();
  let best = 0;
  for (const row of matrix) {
    const first = row[0];
    const key = row.map(c => c ^ first).join(",");
    const next = (count.get(key) || 0) + 1;
    count.set(key, next);
    best = Math.max(best, next);
  }
  return best;
}
class Solution {
    public int maxEqualRowsAfterFlips(int[][] matrix) {
        Map<String, Integer> count = new HashMap<>();
        int best = 0;
        for (int[] row : matrix) {
            int first = row[0];
            StringBuilder sb = new StringBuilder();
            for (int c : row) sb.append(c ^ first);
            String key = sb.toString();
            int next = count.getOrDefault(key, 0) + 1;
            count.put(key, next);
            best = Math.max(best, next);
        }
        return best;
    }
}
int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
    unordered_map<string, int> count;
    int best = 0;
    for (auto& row : matrix) {
        int first = row[0];
        string key;
        for (int c : row) key += ('0' + (c ^ first));
        best = max(best, ++count[key]);
    }
    return best;
}
Time: O(m · n) Space: O(m · n)