Special Positions in a Binary Matrix Problem
#1582
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1582.
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.lengthn == mat[i].length1 <= m, n <= 100mat[i][j]is either0or1.
Solution
Approach: Count Ones per Row and Column
A 1 at (i, j) is special exactly when it is the only 1 in row i and the only 1 in column j. Checking the whole row and column for every 1 would cost O(m + n) per cell. Instead, count first and check later.
- Make one pass over the matrix and record
rows[i], the number of 1s in rowi, andcols[j], the number of 1s in columnj. - Make a second pass. A cell counts when
mat[i][j] == 1,rows[i] == 1andcols[j] == 1.
Since the cell itself is a 1, a count of exactly 1 means every other cell in that row (or column) is 0.
Complexity: O(mn) time and O(m + n) extra space for the two count arrays.
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
rows = [0] * len(mat) # number of 1s in each row
cols = [0] * len(mat[0]) # number of 1s in each column
for i, row in enumerate(mat):
for j, x in enumerate(row):
rows[i] += x
cols[j] += x
ans = 0
for i, row in enumerate(mat):
for j, x in enumerate(row):
if x == 1 and rows[i] == 1 and cols[j] == 1:
ans += 1
return ans