#1582

Special Positions in a Binary Matrix

Easy
ArrayMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking each position multiple times, we can count the number of 1s in each row and column first. This allows us to quickly determine if a position is special in constant time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create two arrays to count the number of 1s in each row and each column.
  2. 2Step 2: Iterate through the matrix to populate these counts.
  3. 3Step 3: Iterate through the matrix again and check if mat[i][j] == 1 and both rowCounts[i] and colCounts[j] are 1.
solution.py20 lines
1# Full working Python code
2mat = [[1,0,0],[0,0,1],[1,0,0]]
3
4def countSpecialPositions(mat):
5    m, n = len(mat), len(mat[0])
6    rowCounts = [0] * m
7    colCounts = [0] * n
8    for i in range(m):
9        for j in range(n):
10            if mat[i][j] == 1:
11                rowCounts[i] += 1
12                colCounts[j] += 1
13    count = 0
14    for i in range(m):
15        for j in range(n):
16            if mat[i][j] == 1 and rowCounts[i] == 1 and colCounts[j] == 1:
17                count += 1
18    return count
19
20print(countSpecialPositions(mat))

Complexity note: The time complexity is O(n) because we only need to iterate through the matrix a couple of times, and the space complexity is O(n) due to the additional arrays used to store counts.

  • 1Counting 1s in rows and columns allows for quick checks.
  • 2Using additional space can lead to significant time savings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.