Sponsored
Sponsored
This approach involves iterating through each element of the matrix and checking if it is '1'. For each such element, all other elements in its row and column are checked to ensure they are '0'. This approach is straightforward but can be optimized.
Time Complexity: O(m * n * (m + n)), where m is the number of rows and n is the number of columns.
Space Complexity: O(1), since we use a constant amount of space.
1def numSpecial(mat):
2 m, n = len(mat), len(mat[0])
3 special_count = 0
4 for i in range(m):
5 for j in range(n):
6 if mat[i][j] == 1:
7 if sum(mat[i][k] for k in range(n)) == 1 and sum(mat[k][j] for k in range(m)) == 1:
8 special_count += 1
9 return special_count
The function numSpecial iterates through the matrix. For each '1', it checks if the sum of the row and column (excluding the current element) is zero. If both are zero, the position is special.
In this approach, two auxiliary arrays are used to track the number of '1's in each row and column. The matrix is then iterated to find the positions where both the row and column contain exactly one '1'. This approach reduces the need for repeatedly checking rows and columns.
Time Complexity: O(m * n), because we only iterate through the matrix twice.
Space Complexity: O(m + n), for storing row and column counts.
1
This JavaScript function builds arrays to record the count of '1's for each row and column. It then checks for special positions using these counts.