Special Positions in a Binary Matrix

easy array matrix

Problem

Given a matrix of 0s and 1s, a position (i, j) is special if mat[i][j] = 1 and all other entries in row i and column j are 0. Return the number of special positions.

Inputmat = [[1,0,0],[0,0,1],[1,0,0]]
Output1
Only (1,2) has a lone 1 in its row and column.

def num_special(mat):
    rows = [sum(r) for r in mat]
    cols = [sum(c) for c in zip(*mat)]
    count = 0
    for i in range(len(mat)):
        for j in range(len(mat[0])):
            if mat[i][j] == 1 and rows[i] == 1 and cols[j] == 1:
                count += 1
    return count
function numSpecial(mat) {
  const m = mat.length, n = mat[0].length;
  const rows = mat.map(r => r.reduce((a, b) => a + b, 0));
  const cols = Array.from({ length: n }, (_, j) => mat.reduce((a, r) => a + r[j], 0));
  let count = 0;
  for (let i = 0; i < m; i++)
    for (let j = 0; j < n; j++)
      if (mat[i][j] === 1 && rows[i] === 1 && cols[j] === 1) count++;
  return count;
}
class Solution {
    public int numSpecial(int[][] mat) {
        int m = mat.length, n = mat[0].length;
        int[] rows = new int[m], cols = new int[n];
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) { rows[i] += mat[i][j]; cols[j] += mat[i][j]; }
        int count = 0;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) count++;
        return count;
    }
}
int numSpecial(vector<vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    vector<int> rows(m), cols(n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++) { rows[i] += mat[i][j]; cols[j] += mat[i][j]; }
    int count = 0;
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) count++;
    return count;
}
Time: O(m · n) Space: O(m + n)