Special Positions in a Binary Matrix - Problem

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).

Input & Output

Example 1 — Basic Matrix
$ Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
Output: 1
💡 Note: Position (1,2) is special: mat[1][2]=1, row 1 has sum 1, column 2 has sum 1
Example 2 — No Special Positions
$ Input: mat = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
💡 Note: All three positions (0,0), (1,1), and (2,2) are special - each has unique row and column
Example 3 — Multiple 1s in Row/Column
$ Input: mat = [[0,0,0,1],[1,0,0,0],[0,1,1,0],[0,0,0,0]]
Output: 2
💡 Note: Positions (0,3) and (1,0) are special, but (2,1) and (2,2) are not because row 2 has multiple 1s

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 ≤ m, n ≤ 100
  • mat[i][j] is either 0 or 1

Visualization

Tap to expand
Special Positions: Find 1s Alone in Row AND ColumnInput Matrix100001100Analysis✓ Position (1,2): Row sum = 1, Column sum = 1✗ Position (0,0): Row sum = 1, Column sum = 2✗ Position (2,0): Row sum = 1, Column sum = 2Result1Special PositionA position is special when it contains 1 AND is the only 1 in its row AND columnOutput: 1
Understanding the Visualization
1
Input Matrix
Binary matrix with 1s and 0s
2
Check Conditions
Find 1s that are alone in row and column
3
Count Special
Count positions meeting both conditions
Key Takeaway
🎯 Key Insight: Pre-calculating row and column sums eliminates redundant work
Asked in
Google 12 Amazon 8 Microsoft 6
28.4K Views
Medium Frequency
~15 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