Python 1072.py
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
def value(row):
result = 0
for r in row:
result <<= 1
result += r
return result
# count rows with the same or complement value
have = defaultdict(int)
for r in matrix:
if r[0] == 0:
have[value(r)] += 1
else: # flip
have[value([ 1 - rr for rr in r ])] += 1
return max(have.values())
Difficulty
and has an acceptance rate of about 79% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a method maxEqualRowsAfterFlips. The method receives a binary matrix and returns the largest number of rows that can be made identical after optionally flipping any subset of columns. The core idea is to treat each row as a binary number, optionally complementing the row when its first element is 1, and then count how many rows share the same resulting pattern. The highest frequency among these patterns is the answer.
Key Steps
Converting a Row to an Integer
A helper function value translates a list of bits into a single integer. The function iterates over the bits, left-shifting the accumulator and adding the current bit. This compact representation enables fast dictionary look-ups.
def value(row):
result = 0
for r in row:
result <<= 1
result += r
return result
Normalising Rows
Rows are normalised so that rows beginning with 0 are kept as-is, while rows beginning with 1 are complemented (each bit b becomes 1-b). This guarantees that two rows that can be made identical by column flips will map to the same integer key.
if r[0] == 0:
have[value(r)] += 1
else: # flip
have[value([1 - rr for rr in r])] += 1
Counting Equivalent Patterns
A defaultdict(int) named have accumulates the frequency of each normalised integer representation. After processing all rows, the maximum value in this dictionary corresponds to the largest group of rows that can be aligned by column flips.
have = defaultdict(int)
# ... row processing loop ...
return max(have.values())
Edge Cases Handled
When a row starts with 0, the algorithm records its original binary pattern directly. When a row starts with 1, the complement operation transforms it into a pattern that would match any other row that could be aligned by flipping the same set of columns. This dual handling naturally covers cases such as rows that are already identical, rows that are exact complements of each other, and rows that consist entirely of 0s or 1s. The use of defaultdict ensures that rows with unique patterns are still counted without additional checks.
Performance Optimizations
The conversion of rows to integers using bitwise left-shifts avoids constructing intermediate strings or tuples, resulting in minimal overhead per element. The complement operation is performed with a concise list comprehension, creating a new list only when necessary (i.e., for rows whose first element is 1). Storing counts in a hash map (defaultdict) provides constant-time updates and look-ups, allowing the method to process the entire matrix in a single pass. The final max call scans the dictionary values once to obtain the answer, keeping the overall work proportional to the number of rows.
ELI5 - Simplified Explanation
Imagine a grid full of little light switches that can be either on or off, represented by zeros and ones. This code looks at every row in that grid and tries to figure out how many rows can end up looking exactly the same by flipping all the switches in a row at once.
First, there is a small helper tool that turns a row of numbers into a single special code. It looks at the row from left to right and builds a unique number to represent the pattern of switches.
The code then goes through every row in the big grid one by one. If a row starts with a zero, it keeps the pattern just as it is. If the row starts with a one, it pretends to flip every switch so that all the ones become zeros and all the zeros become ones. This makes sure that rows with the same pattern but different starting numbers are treated as twins.
As it finds these patterns, it keeps a tally in a notepad to remember how many times each specific pattern shows up. Once every row has been checked and its pattern added to the notepad, the code looks at the tally to find which pattern appeared the most often. That tells you the most rows that could become identical after flipping.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| suxrobGM | C# | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| Shamik07 | Dart | ||||||||
| suxrobGM | C# |
Videos
Solved On The Same Day
- problem 2043: Simple Bank System
- problem 2074: Reverse Nodes in Even Length Groups
- problem 2091: Removing Minimum and Maximum From Array
- problem 2517: Maximum Tastiness of Candy Basket
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality