#1072
Flip Columns For Maximum Number of Equal Rows
MediumArrayHash TableMatrixHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n) |
| Space | O(1) | O(m) |
💡
Intuition
Time O(m * n)Space O(m)
Instead of checking all combinations, we can use a HashMap to count the frequency of each unique row pattern after normalizing them based on the first column. This way, we can directly count how many rows can be made equal with the same flips.
⚙️
Algorithm
4 steps- 1Step 1: Create a HashMap to store the frequency of each unique row pattern.
- 2Step 2: For each row, create a normalized version by flipping it based on the first element.
- 3Step 3: Count the occurrences of each normalized row in the HashMap.
- 4Step 4: The maximum value in the HashMap is the answer.
solution.py9 lines
1from collections import defaultdict
2
3def maxEqualRowsAfterFlips(matrix):
4 count = defaultdict(int)
5 for row in matrix:
6 # Normalize row based on the first element
7 normalized = tuple((cell ^ row[0]) for cell in row)
8 count[normalized] += 1
9 return max(count.values())ℹ
Complexity note: The time complexity is O(m * n) because we process each row and each element in the row once. The space complexity is O(m) due to the storage of the HashMap for unique row patterns.
- 1Flipping columns can be seen as normalizing the rows based on the first column's value.
- 2Using a HashMap allows us to efficiently count and compare row patterns.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.