Flip Columns For Maximum Number of Equal Rows - Problem

Imagine you have a binary matrix (containing only 0s and 1s) and you possess a magical power: you can flip entire columns at will! When you flip a column, every 0 becomes a 1 and every 1 becomes a 0 in that column.

Your goal is to strategically choose which columns to flip so that you maximize the number of rows that become uniform (all 0s or all 1s). Think of it as organizing a binary pattern to create the most harmony possible!

Input: An m ร— n binary matrix
Output: The maximum number of rows that can be made uniform after optimally flipping columns

Example: If you have matrix [[0,1],[1,1]], you can flip column 0 to get [[1,1],[0,1]], making the first row uniform. The answer would be 1.

Input & Output

example_1.py โ€” Basic Matrix
$ Input: matrix = [[0,1],[1,1]]
โ€บ Output: 1
๐Ÿ’ก Note: After flipping column 0, we get [[1,1],[0,1]]. The first row becomes uniform (all 1s), so the answer is 1.
example_2.py โ€” Larger Matrix
$ Input: matrix = [[0,1,0],[1,0,1],[1,0,0]]
โ€บ Output: 2
๐Ÿ’ก Note: Rows [0,1,0] and [1,0,1] are complements of each other. By flipping appropriate columns, both can be made uniform, giving us 2 equal rows.
example_3.py โ€” All Same Pattern
$ Input: matrix = [[0,0,0],[0,0,0],[0,0,0]]
โ€บ Output: 3
๐Ÿ’ก Note: All rows are already uniform (all 0s), so we don't need to flip any columns. The answer is 3.

Constraints

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

Visualization

Tap to expand
Visual Solution: Pattern GroupingStep 1: Original Matrix with Patterns010Row 1101Row 2110Row 3001Row 4โ†“ Find Complements โ†“010โ†”101101โ†”010110โ†”001001โ†”110Step 2: Group by Canonical PatternsGroup A: Pattern 010Rows 1 & 2 (complements)Count: 2Group B: Pattern 001Rows 3 & 4 (complements)Count: 2Maximum Group SizeAnswer: 2
Understanding the Visualization
1
Identify Patterns
Each row has a binary pattern, like a unique fingerprint
2
Find Complements
For each pattern, create its opposite (0โ†’1, 1โ†’0)
3
Group Compatible Rows
Rows that are complements of each other can become identical after column flips
4
Count Maximum Group
The largest group represents the maximum achievable uniform rows
Key Takeaway
๐ŸŽฏ Key Insight: Rows that are binary complements of each other can always be made identical by choosing the right column flips. We group compatible rows and find the largest group.
Asked in
Google 25 Amazon 18 Microsoft 12 Meta 8
28.5K Views
Medium Frequency
~18 min Avg. Time
892 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