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

Leetcode #2123: Minimum Operations to Remove Adjacent Ones in Matrix

In this guide, we solve Leetcode #2123 Minimum Operations to Remove Adjacent Ones in Matrix 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 a 0-indexed binary matrix grid. In one operation, you can flip any 1 in grid to be 0.

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Graph, Array, Matrix

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

Input: grid = [[1,1,0],[0,1,1],[1,1,1]] Output: 3 Explanation: Use 3 operations to change grid[0][1], grid[1][2], and grid[2][1] to 0. After, no more 1's are 4-directionally connected and grid is well-isolated.

Python Solution

class Solution: def minimumOperations(self, grid: List[List[int]]) -> int: def find(i: int) -> int: for j in g[i]: if j not in vis: vis.add(j) if match[j] == -1 or find(match[j]): match[j] = i return 1 return 0 g = defaultdict(list) m, n = len(grid), len(grid[0]) for i, row in enumerate(grid): for j, v in enumerate(row): if (i + j) % 2 and v: x = i * n + j if i < m - 1 and grid[i + 1][j]: g[x].append(x + n) if i and grid[i - 1][j]: g[x].append(x - n) if j < n - 1 and grid[i][j + 1]: g[x].append(x + 1) if j and grid[i][j - 1]: g[x].append(x - 1) match = [-1] * (m * n) ans = 0 for i in g.keys(): vis = set() ans += find(i) return ans

Complexity

The time complexity is O(m×n)O(m \times n)O(m×n), where nnn and mmm are the number of 111s in the matrix and the number of edges, respectively. The space complexity is O(V).

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