Given an m x n
binary matrix mat
, return the number of special positions in mat
.
A position (i, j)
is called special if mat[i][j] == 1
and all other elements in row i
and column j
are 0
(rows and columns are 0-indexed).
Example 1:
Input: mat = [[1,0,0],[0,0,1],[1,0,0]] Output: 1 Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
Example 2:
Input: mat = [[1,0,0],[0,1,0],[0,0,1]] Output: 3 Explanation: (0, 0), (1, 1) and (2, 2) are special positions.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
mat[i][j]
is either 0
or 1
.The problem asks to find the number of "special positions" in a binary matrix. A special position (i, j) is where the element mat[i][j]
is 1, and all other elements in the same row (i) and column (j) are 0.
The most efficient approach is a counting method with linear time complexity. Here's a breakdown of the algorithm:
1. Row and Column Sums:
rows
to store the sum of elements in each row and cols
to store the sum of elements in each column.rows[i]
and cols[j]
for each element mat[i][j]
that is 1. This efficiently counts the number of 1s in each row and column.2. Identifying Special Positions:
mat[i][j]
that is 1, we check two conditions:
rows[i] == 1
: This verifies that there's only one 1 in the current row.cols[j] == 1
: This verifies that there's only one 1 in the current column.ans
counter.3. Return the Count:
ans
, which represents the total number of special positions found.Time Complexity Analysis:
The algorithm involves two iterations over the matrix. Each iteration takes O(mn) time, where 'm' is the number of rows and 'n' is the number of columns. The other operations (initializing arrays, checking conditions) are linear in the size of the matrix, making them O(m+n). Thus, the overall time complexity is **O(mn)**, which is linear to the size of the input matrix.
Space Complexity Analysis:
The space complexity is determined by the size of the rows
and cols
arrays. These arrays have sizes 'm' and 'n', respectively. Therefore, the space complexity is O(m+n), which is linear to the dimensions of the matrix.
Code Examples (with explanations):
The code provided in the various programming languages implements this algorithm. They all follow the same structure:
rows
and cols
are created and initialized to zero.ans
variable, which keeps count of special positions, is returned.The comments in the code further clarify each step. The choice of language doesn't significantly impact the algorithmic approach or the complexity analysis. All examples provide the same efficient solution.