Skip to content

1072. Flip Columns For Maximum Number of Equal Rows

Description

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.length
  • n == matrix[i].length
  • 1 <= m, n <= 300
  • matrix[i][j] is either 0 or 1.

 

Solutions

Solution: Hash Map

  • Time complexity: O(mn)
  • Space complexity: O(m)

 

JavaScript

js
/**
 * @param {number[][]} matrix
 * @return {number}
 */
const maxEqualRowsAfterFlips = function (matrix) {
  const m = matrix.length;
  const n = matrix[0].length;
  const rowMap = new Map();
  let result = 0;

  for (let row = 0; row < m; row++) {
    const isFlip = matrix[row][0];
    let current = '';

    for (let col = 0; col < n; col++) {
      const value = matrix[row][col];
      const flipValue = isFlip ? value ^ 1 : value;

      current += `${flipValue}`;
    }
    const sameRowCount = rowMap.get(current) ?? 0;

    rowMap.set(current, sameRowCount + 1);
    result = Math.max(sameRowCount + 1, result);
  }
  return result;
};

Released under the MIT license