You are given an m x n
binary matrix mat
of 1’s (representing soldiers) and 0’s (representing civilians). A position (i, j)
is called a “special position” if mat[i][j]
== 1 and all other elements in row i
and column j
are 0.
Return the number of special positions in mat
.
1 <= m, n <= 100
.To find the number of special positions, we need to:
The plan is:
def numSpecial(mat):
m, n = len(mat), len(mat[0])
special_positions = 0
for i in range(m):
for j in range(n):
if mat[i][j] == 1:
row_special = all(mat[i][k] == 0 for k in range(n) if k != j)
col_special = all(mat[k][j] == 0 for k in range(m) if k != i)
if row_special and col_special:
special_positions += 1
return special_positions
# Example usage:
mat = [
[1, 0, 0],
[0, 0, 1],
[1, 0, 0]
]
print(numSpecial(mat)) # Output should be 1
O(m * n)
where m
is the number of rows and n
is the number of columns.O(m + n)
O((m * n) * (m + n))
.In summary:
O((m * n) * (m + n))
.O(1)
in terms of space.O(1)
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?