Remove All Ones With Row and Column Flips - 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).

Return true if it is possible to remove all 1's from grid using any number of operations or false otherwise.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[0,1],[0,1]]
Output: true
💡 Note: Both rows are identical [0,1]. We can flip column 1 to make all rows [0,0], then they're all zeros.
Example 2 — Complementary Rows
$ Input: grid = [[0,1],[1,0]]
Output: true
💡 Note: Row 2 is the complement of Row 1. We can flip all columns to make both rows [1,0], then flip both rows to get all zeros.
Example 3 — Impossible Case
$ Input: grid = [[0,0],[1,1],[0,1]]
Output: false
💡 Note: Row 3 [0,1] is neither identical nor complementary to Row 1 [0,0]. Cannot be made consistent through flips.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 300
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
Remove All Ones With Row and Column Flips INPUT Binary Matrix (m x n): 0 1 0 1 R0 R1 C0 C1 grid = [[0,1],[0,1]] Row Patterns: Row 0: [0,1] Row 1: [0,1] Same pattern! ALGORITHM STEPS 1 Extract Patterns Get pattern of each row 2 Normalize Rows If row[0]=1, flip entire row 3 Compare Patterns All rows must match 4 Return Result True if all same Pattern Analysis: Row 0: [0,1] Row 1: [0,1] Patterns Match = OK FINAL RESULT After flipping Column 1: 0 0 0 0 flipped Output: true All 1s removed! Operation: Flip Col 1 OK Key Insight: If we can remove all 1s, then all rows must have the same pattern or be complements of each other. Flipping a row inverts its pattern. Flipping a column inverts that position in ALL rows equally. So if patterns match (or are exact complements), we can make all zeros. Time: O(m*n) TutorialsPoint - Remove All Ones With Row and Column Flips | Row Pattern Analysis
Asked in
Google 15 Amazon 8 Microsoft 12
23.4K Views
Medium Frequency
~25 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen