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 in a Binary Matrix INPUT Binary Matrix (3x3) 1 0 0 0 0 1 1 0 0 Row 0 Row 1 Row 2 mat = [[1,0,0], [0,0,1], [1,0,0]] Special Position Regular Cell ALGORITHM STEPS 1 Pre-calculate Row Sums rowSum = [1, 1, 1] 2 Pre-calculate Col Sums colSum = [2, 0, 1] 3 Check Each Cell If mat[i][j]==1 and both rowSum[i]==1, colSum[j]==1 4 Count Special Positions Increment counter Position Analysis Pos Row Col Special? (0,0) 1 2 NO (1,2) 1 1 OK (2,0) 1 2 NO colSum[0]=2 means col 0 has 2 ones FINAL RESULT Special Position Found 1 0 0 0 0 1 * 1 0 0 col has 2 ones Output: 1 Only position (1,2) is special: Row 1 sum = 1, Col 2 sum = 1 Both conditions satisfied! Key Insight: Pre-calculating row and column sums allows O(1) lookup for each cell check. A cell (i,j) is special if mat[i][j]=1, rowSum[i]=1, and colSum[j]=1 (only one '1' in row AND column). Time: O(m*n) | Space: O(m+n) for storing row and column sums TutorialsPoint - Special Positions in a Binary Matrix | Pre-calculate Sums Approach
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