Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Special Positions In A Binary Matrix

Count the cells in a binary matrix that are the only 1 in both their row and their column.

Acceptance 100%
Problem Statement

Given an m×nm \times n binary matrix, count how many cells contain a 1 such that every other cell in the same row and every other cell in the same column is 0.

A cell is considered special if it is the only 1 in its row and also the only 1 in its column.

Input Format

  • A binary matrix mat with m rows and n columns.
  • Each entry is either 0 or 1.

You may assume the matrix is non-empty.

Output Format

  • Return the number of special positions in the matrix.

Constraints

  • 1m,n1 \le m, n
  • mat[i][j] is either 0 or 1
  • The matrix size is small enough for an O(mn)O(mn) solution
Examples
Sample cases returned by the problem API.

Example 1

Input

mat = [[1,0,0],[0,0,1],[1,0,0]]

Output

1

Explanation

The only special position is at row 2, column 3 (0-indexed: [1][2]). It is the only 1 in its row and its column.

Example 2

Input

mat = [[1,0,0],[0,1,0],[0,0,1]]

Output

3

Explanation

Each diagonal 1 is the only 1 in both its row and its column.

Show 1 more example

Example 3

Input

mat = [[0,0],[0,0]]

Output

0

Explanation

There are no 1s, so there are no special positions.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.