Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2128: Remove All Ones With Row and Column Flips

In this guide, we solve Leetcode #2128 Remove All Ones With Row and Column Flips in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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).

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Bit Manipulation, Array, Math, Matrix

Intuition

The problem structure lets us track state with bitwise operations.

Bit operations are constant time and avoid extra memory.

Approach

Apply XOR/AND/OR and shifts to maintain the required invariant.

Aggregate the result in a single pass.

Steps:

  • Identify a bitwise invariant.
  • Combine values with bit operations.
  • Return the aggregated result.

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: - Flip the middle row - Flip the middle column

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

Complexity

The time complexity is O(mn)O(mn)O(mn) and the space complexity is O(m)O(m)O(m), where mmm and nnn are the number of rows and columns in the matrix, respectively. The space complexity is O(m)O(m)O(m), where mmm and nnn are the number of rows and columns in the matrix, respectively.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy