Problem Description
Given an m x n binary matrix mat, determine the number of special positions in mat. A position (i, j) is special if mat[i][j] == 1 and every other element in row i and column j is 0.
Key Insights
- Pre-compute the sum of 1s in each row and each column.
- A position with a 1 is special only if its corresponding row and column each have exactly one 1.
- This method avoids nested loops checking full rows and columns repeatedly.
Space and Time Complexity
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. Space Complexity: O(m + n) for storing the row and column counts.
Solution
The solution involves two main passes over the matrix. First, iterate over the matrix to calculate the number of 1s for each row and each column using arrays (or lists). In the second pass, check every position; if it contains a 1 and its corresponding row and column counts are both 1, then it is a special position. The use of precomputed counts eliminates the need for redundant traversal of rows and columns, significantly improving efficiency. The key trick here is leveraging auxiliary arrays to store the frequency of 1s, thereby reducing the time complexity of checking each special position.