Amazon Interview Question | Java | 73. Set Matrix Zeroes

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-04-07Added By Anonymous
Source: Link

Company: Amazon
Role: unknown
Interview Stage: unknown
Location: unknown
Year: unknown

Original Post Content:

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

You must do it in place.

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

[Image reference: https://assets.leetcode.com/users/images/e163d3ad-7bbe-4441-889d-96d60d217afd_1712511012.4467676.jpeg]

Constraints:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1

class Solution {
public void setZeroes(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;

int[] row = new int[n]; // row array
int[] col = new int[m]; // col array

// Traverse the matrix:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
// mark ith index of row wih 1:
row[i] = 1;

// mark jth index of col wih 1:
col[j] = 1;
}
}
}

// Finally, mark all (i, j) as 0
// if row[i] or col[j] is marked with 1.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (row[i] == 1 || col[j] == 1) {
matrix[i][j] = 0;
}
}
}
}
}

Comments