Remove All Ones With Row and Column Flips — LeetCode 2128 Python Solution
- Problem
- #2128
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an m x n binary matrix grid. In one operation, you can choose any row or column and flip 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,1,0],[1,0,1],[0,1,0]]
- Output
- true
- Explanation
- One possible way to remove all 1's from grid is to:
Python solution
class Solution:
def removeOnes(self, grid: List[List[int]]) -> bool:
s = set()
for row in grid:
t = tuple(row) if row[0] == grid[0][0] else tuple(x ^ 1 for x in row)
s.add(t)
return len(s) == 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(mn) |
| Space | O(m), where m and n are the number of rows and columns in the matrix, respectively auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2128. Remove All Ones With Row and Column Flips is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2128. Remove All Ones With Row and Column Flips?
- LeetCode 2128. Remove All Ones With Row and Column Flips is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2128. Remove All Ones With Row and Column Flips?
- The Python solution on this page runs in O(mn).
- What is the space complexity of LeetCode 2128. Remove All Ones With Row and Column Flips?
- The Python solution on this page uses O(m), where m and n are the number of rows and columns in the matrix, respectively auxiliary space.
- What topics does LeetCode 2128. Remove All Ones With Row and Column Flips cover?
- LeetCode 2128. Remove All Ones With Row and Column Flips is tagged Bit Manipulation, Array, Math and Matrix on LeetCode.
- Is LeetCode 2128. Remove All Ones With Row and Column Flips a premium problem?
- Yes. LeetCode 2128. Remove All Ones With Row and Column Flips is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.