MediumNo. 0861
Score After Flipping Matrix — LeetCode 861 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Greedy, Bit Manipulation, Array, Matrix
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an m x n binary matrix grid. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Example
- Input
- grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
- Output
- 39
- Explanation
- 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Python solution
class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
for i in range(m):
if grid[i][0] == 0:
for j in range(n):
grid[i][j] ^= 1
ans = 0
for j in range(n):
cnt = sum(grid[i][j] for i in range(m))
ans += max(cnt, m - cnt) * (1 << (n - j - 1))
return ansComplexity
- Time
- O(n log n)
- Space · auxiliary
- O(1) to O(n)
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 861. Score After Flipping Matrix is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0807 | Max Increase to Keep City Skyline | Medium |
| 1253 | Reconstruct a 2-Row Binary Matrix | Medium |
| 1536 | Minimum Swaps to Arrange a Binary Grid | Medium |
| 1558 | Minimum Numbers of Function Calls to Make Target Array | Medium |
| 1605 | Find Valid Matrix Given Row and Column Sums | Medium |
| 1727 | Largest Submatrix With Rearrangements | Medium |
Frequently asked questions
- How hard is LeetCode 861. Score After Flipping Matrix?
LeetCode 861. Score After Flipping Matrix is rated Medium on LeetCode.
- What topics does LeetCode 861. Score After Flipping Matrix cover?
LeetCode 861. Score After Flipping Matrix is tagged Greedy, Bit Manipulation, Array and Matrix on LeetCode.