LeetCode Solutions

1072. Flip Columns For Maximum Number of Equal Rows

Time:

Space:

			

class Solution {
 public:
  int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    int ans = 0;
    vector<int> flip(n);
    unordered_set<int> seen;

    for (int i = 0; i < m; ++i) {
      if (seen.count(i))
        continue;
      int count = 0;
      for (int j = 0; j < n; ++j)
        flip[j] = 1 ^ matrix[i][j];
      for (int k = 0; k < m; ++k)
        if (matrix[k] == matrix[i] || matrix[k] == flip) {
          seen.insert(k);
          ++count;
        }
      ans = max(ans, count);
    }

    return ans;
  }
};
			

class Solution {
  public int maxEqualRowsAfterFlips(int[][] matrix) {
    final int m = matrix.length;
    final int n = matrix[0].length;
    int ans = 0;
    int[] flip = new int[n];
    Set<Integer> seen = new HashSet<>();

    for (int i = 0; i < m; ++i) {
      if (seen.contains(i))
        continue;
      int count = 0;
      for (int j = 0; j < n; ++j)
        flip[j] = 1 ^ matrix[i][j];
      for (int k = 0; k < m; ++k)
        if (Arrays.equals(matrix[k], matrix[i]) || Arrays.equals(matrix[k], flip)) {
          seen.add(k);
          ++count;
        }
      ans = Math.max(ans, count);
    }

    return ans;
  }
}
			

class Solution:
  def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
    patterns = [tuple(a ^ row[0] for a in row) for row in matrix]
    return max(Counter(patterns).values())