Special Positions in a Binary Matrix

Easy · Matrix · Array · Matrix

Problem

You are given an m x n binary matrix mat. A position (i, j) is special when mat[i][j] == 1 and every other cell in row i and every other cell in column j is 0.

Return the number of special positions in mat.

Examples

Input: mat = [[0,0,1],[1,0,0],[0,0,1]]
Output: 1

Only (1,0) is special: the two 1s in column 2 share a column.

Input: mat = [[1,0],[0,1]]
Output: 2

Both 1s are alone in their row and their column.

Input: mat = [[1,1,0],[0,0,0],[0,0,1]]
Output: 1

The 1s in row 0 share a row; the 1 at (2,2) is alone, so the answer is 1.

Constraints

Approaches

Follow-up

Only two numbers per line matter: the count of ones. The same precompute-then-check idea answers "how many 1s have exactly k ones in their row and column", and works on pictures written as strings; both are use cases below.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…