/**
* Problem: LeetCode 1582 - Special Positions in a Binary Matrix
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int numSpecial(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[] rowSum = new int[m];
int[] colSum = new int[n];
// Step 1: Precompute the count of 1s in each row and column
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
rowSum[i]++;
colSum[j]++;
}
}
}
// Step 2: Identify special positions where mat[i][j] == 1 and rowSum == 1 and colSum == 1
int specialCount = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1 && rowSum[i] == 1 && colSum[j] == 1) {
specialCount++;
}
}
}
return specialCount;
}
}
"""
Problem: LeetCode 1582 - Special Positions in a Binary Matrix
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
row_sum = [sum(row) for row in mat]
col_sum = [sum(mat[i][j] for i in range(m)) for j in range(n)]
special_count = 0
for i in range(m):
if row_sum[i] == 1:
for j in range(n):
if mat[i][j] == 1 and col_sum[j] == 1:
special_count += 1
return special_count
/**
* Problem: LeetCode 1582 - Special Positions in a Binary Matrix
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
vector<int> rowSum(m, 0);
vector<int> colSum(n, 0);
// Step 1: Compute row and column sums
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1) {
rowSum[i]++;
colSum[j]++;
}
}
}
// Step 2: Count special positions
int specialCount = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (mat[i][j] == 1 && rowSum[i] == 1 && colSum[j] == 1) {
specialCount++;
}
}
}
return specialCount;
}
};
/**
* Problem: LeetCode 1582 - Special Positions in a Binary Matrix
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[][]} mat
* @return {number}
*/
var numSpecial = function(mat) {
const m = mat.length;
const n = mat[0].length;
const rowSum = new Array(m).fill(0);
const colSum = new Array(n).fill(0);
// Step 1: Precompute frequency of 1s in each row and column
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (mat[i][j] === 1) {
rowSum[i]++;
colSum[j]++;
}
}
}
// Step 2: Count cells that uniquely hold the single 1 in both their row and column
let specialCount = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (mat[i][j] === 1 && rowSum[i] === 1 && colSum[j] === 1) {
specialCount++;
}
}
}
return specialCount;
};