Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 4, 2026 17:59
Show Gist options
  • Select an option

  • Save tatsuyax25/240ad720b38c02239e2166ed94f1f0e1 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/240ad720b38c02239e2166ed94f1f0e1 to your computer and use it in GitHub Desktop.
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).
/**
* @param {number[][]} mat
* @return {number}
*/
var numSpecial = function(mat) {
const m = mat.length;
const n = mat[0].length;
// Count how many 1s appear in each row
const rowCount = new Array(m).fill(0);
// Count how many 1s appear in each column
const colCount = new Array(n).fill(0);
// First pass: fill rowCount and colCount
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (mat[i][j] === 1) {
rowCount[i]++;
colCount[j]++;
}
}
}
let specialCount = 0;
// Second pass: check which 1s are special
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
// A cell is special if:
// - it's a 1
// - its row has exactly one 1
// - its column has exactly one 1
if (mat[i][j] === 1 && rowCount[i] === 1 && colCount[j] === 1) {
specialCount++;
}
}
}
return specialCount;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment