Set Matrix Zeroes

How to Solve the “Set Matrix Zeroes” Problem Efficiently

Matrix manipulation problems are common in coding interviews, often testing your ability to work with multidimensional data and optimize space usage.

One such problem is Set Matrix Zeroes, where the goal is to modify the matrix in-place to set entire rows and columns to zero if any element is zero. Let’s explore the problem and its solutions step-by-step.

Set Matrix zero

Problem Statement

You are given an ( m×n ) matrix of integers, matrix. If any element in the matrix is 0, set its entire row and column to 0. The update must be performed in-place, meaning you cannot use extra space for another matrix.

  • 1 <= matrix.length, matrix[0].length <= 100
  • -2^31 <= matrix[i][j] <= (2^31) – 1
Set Zero Matrix

Explanation:
Explanation:
The range [0, 3] contains the numbers {0, 1, 2, 3}. The number 0 is missing from the array nums.

Set Zero Matrix 1

Explanation:
The range [0, 2] includes the numbers {0, 1, 2}. The number 1 is missing.

There are mainly three approach to solve this problem – 

  1. Brute Force
  2. Iteration
  3. Iteration (Space Optimized)

1. Brute Force 

  • Time complexity: O(mn)
  • Space complexity:O(mn)

Where m is the number of rows and n is the number of columns.

2. Iteration

Time & Space Complexity
  • Time complexity: O(m∗n)
  • Space complexity: O(m+n)

Where m is the number of rows and n is the number of columns.

Code

3. Fast And Slow Pointers – II

  • Time complexity: O(m∗n)
  • Space complexity: O(1)

Where m is the number of rows and n is the number of columns.

Code

More Articles