Leetcode 1582. Special Positions in a Binary Matrix
You are given an m x n
binary matrix mat
of 1
’s (representing soldiers) and 0
’s (representing civilians). A position (i, j)
in the matrix is called special if:
mat[i][j] == 1
, andi
and column j
are 0.Return the number of special positions in the matrix.
Input:
mat = [
[1,0,0],
[0,0,1],
[1,0,0]
]
Output: 1
Explanation:
(1, 2) is a special position because it is '1' and all other elements in the row and column are 0.
mat
is guaranteed to have at least one element (m >= 1 and n >= 1).1
, we’ll check all other elements in its row and column.public class Solution {
public int numSpecial(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int specialCount = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
boolean isSpecial = true;
// Check row i
for (int k = 0; k < n; k++) {
if (k != j && mat[i][k] == 1) {
isSpecial = false;
break;
}
}
// Check column j
if (isSpecial) {
for (int k = 0; k < m; k++) {
if (k != i && mat[k][j] == 1) {
isSpecial = false;
break;
}
}
}
if (isSpecial) {
specialCount++;
}
}
}
}
return specialCount;
}
}
O(m * n)
where m
is the number of rows and n
is the number of columns.O(n)
and O(m)
respectively. Therefore, it becomes O(m * n * (m + n))
in the worst case, but improvements can be made.A possible optimization could involve precomputing the sum of rows and columns to quickly check if they contain another ‘1’.
Would you like to proceed with the optimized version?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?