Flip Columns For Maximum Number of Equal Rows - Problem

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.

A row has all values equal if all cells in that row are either 0 or 1.

Input & Output

Example 1 — Basic Case
$ Input: matrix = [[0,1],[1,1]]
Output: 1
💡 Note: We can flip column 0 to make row 1 become [1,1] (uniform), or flip column 1 to make row 1 become [0,0] (uniform). Either way, maximum 1 row can be uniform.
Example 2 — Multiple Uniform Rows
$ Input: matrix = [[0,1],[1,0]]
Output: 2
💡 Note: Flipping column 0 makes both rows uniform: [1,1] and [0,0]. Both patterns [0,1] and [1,0] are complements, so they can both become uniform with the same flip.
Example 3 — Already Uniform
$ Input: matrix = [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
💡 Note: Row 1 [0,0,1] and row 3 [1,1,0] are complements of each other, so they can both be made uniform with the same column flips. Row 1 [0,0,0] forms its own group. Maximum uniform rows achievable is 2.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 300
  • matrix[i][j] is either 0 or 1

Visualization

Tap to expand
Flip Columns For Maximum Equal Rows INPUT Binary Matrix (2x2) 0 1 1 1 R0 R1 C0 C1 matrix = [ [0, 1], [1, 1] ] Row 0: [0,1] - Not equal Row 1: [1,1] - All equal ALGORITHM STEPS 1 Pattern Detection Find row pattern or complement pattern 2 Normalize Rows Row 0: "01" or flip "10" Row 1: "11" or flip "00" 3 Count Patterns Group rows by pattern Same pattern = same flips Pattern Count "01"/"10" 1 "11"/"00" 1 4 Return Max Count Max group size = answer FINAL RESULT Best Strategy Analysis No Columns Flipped Row 0: [0,1] X Row 1: [1,1] OK Flip Column 0 Row 0: [1,1] OK Row 1: [0,1] X Maximum Rows: 1 Only 1 row can have all equal values Key Insight: Rows that can become equal after same column flips share a pattern. Two rows match if one equals the other OR its bitwise complement. Count matching patterns using HashMap. Max count = answer. Time: O(m*n), Space: O(m*n) TutorialsPoint - Flip Columns For Maximum Number of Equal Rows | Optimal Solution
Asked in
Google 8 Amazon 5
26.7K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen