LeetCode: Special Positions in a Binary Matrix Solution
Count number of 1sApproach
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 = 089 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 }1718 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] === 124 // boolean coerce to 1 if true, 0 if false25 }26 }2728 return res29}
References
Similar problems
N/A
Comments
Loading comments...
Tags
leetcode
array
matrix
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.