LeetCode: Special Positions in a Binary Matrix Solution

Count number of 1s

Approach

Count number of 1s in each row, column

A special position is the position that

  • has the value of 1
  • number of 1s in its row and column are both 1

Implementation

1var numSpecial = function (mat) {
2 const [m, n] = [mat.length, mat[0].length]
3 const [numberOf1sInRow, numberOf1sInCol] = [
4 new Uint8Array(m),
5 new Uint8Array(n),
6 ]
7 let res = 0
8
9 for (let row = 0; row < m; row++) {
10 for (let col = 0; col < n; col++) {
11 if (mat[row][col]) {
12 numberOf1sInRow[row]++
13 numberOf1sInCol[col]++
14 }
15 }
16 }
17
18 for (let row = 0; row < m; row++) {
19 for (let col = 0; col < n; col++) {
20 res +=
21 mat[row][col] &&
22 numberOf1sInRow[row] === 1 &&
23 numberOf1sInCol[col] === 1
24 // boolean coerce to 1 if true, 0 if false
25 }
26 }
27
28 return res
29}

References

Original problem

Similar problems

N/A

Comments

Loading comments...

Tags

leetcode

array

matrix

Next Post

LeetCode: Partition Equal Subset Sum

Memoized recursion

HoningJS

Search Posts