Remove All Ones With Row and Column Flips — LeetCode 2128 Python Solution

MediumLeetCode PremiumBit ManipulationArrayMathMatrix
Problem
#2128
Reading time
2 min

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

Python
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) == 1

Complexity

MeasureComplexity
TimeO(mn)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview