Special Positions in a Binary Matrix - Problem
You're given an m ร n binary matrix where each cell contains either 0 or 1. Your task is to find all the "special positions" in this matrix.
A position (i, j) is considered special if:
- The cell at
mat[i][j]contains a1 - All other elements in row
iare0 - All other elements in column
jare0
In other words, a special position is like finding a unique lighthouse in a grid - it's the only light (1) in both its row and column!
Goal: Return the total count of special positions in the matrix.
Input & Output
example_1.py โ Basic Matrix
$
Input:
mat = [[1,0,0],[0,0,1],[1,0,0]]
โบ
Output:
1
๐ก Note:
Position (1,2) has value 1, is the only 1 in row 1, and the only 1 in column 2, making it special. Other 1s share their columns with other 1s.
example_2.py โ Multiple Special
$
Input:
mat = [[1,0,0],[0,1,0],[0,0,1]]
โบ
Output:
3
๐ก Note:
This is a diagonal matrix where each 1 is the only 1 in both its row and column. All three positions (0,0), (1,1), and (2,2) are special.
example_3.py โ No Special Positions
$
Input:
mat = [[0,0],[0,0]]
โบ
Output:
0
๐ก Note:
Matrix contains only zeros, so there are no 1s and therefore no special positions possible.
Constraints
- m == mat.length
- n == mat[i].length
- 1 โค m, n โค 100
- mat[i][j] is either 0 or 1
- Each cell contains exactly one binary digit
Visualization
Tap to expand
Understanding the Visualization
1
Scan the Ocean
Look at each territory in the grid to find all lighthouses (1s)
2
Check Isolation
For each lighthouse, verify it's the only one in its row AND column
3
Count Special Lighthouses
Increment counter for each lighthouse that meets both isolation criteria
Key Takeaway
๐ฏ Key Insight: Pre-calculating row and column sums allows us to determine if a lighthouse is special in constant time, transforming an O(mยฒnยฒ) problem into O(mn).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code