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 a 1
  • All other elements in row i are 0
  • All other elements in column j are 0

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
๐Ÿ—ผ Finding Special Lighthouses in Ocean Grid๐Ÿ—ผ~~~~๐Ÿ—ผ๐Ÿ—ผ~~โŒ Not special: column has 2 lighthousesโœ… Special: alone in row AND column๐ŸŽฏ Found 1 special lighthouse!
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).
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
28.5K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen