Special Positions in a Binary Matrix - Array - Easy - LeetCode
💻 coding

Special Positions in a Binary Matrix - Array - Easy - LeetCode

1 min read 237 words
1 min read
ShareWhatsAppPost on X
  • 1A special position in a binary matrix is defined as an element that is 1, with all other elements in its row and column being 0.
  • 2The algorithm counts special positions by maintaining row and column counts for each element in the matrix.
  • 3The time complexity of the solution is O(n) and the space complexity is O(n), making it efficient for the given constraints.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A special position in a binary matrix is defined as an element that is 1, with all other elements in its row and column being 0."

Special Positions in a Binary Matrix - Array - Easy - LeetCode

Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, 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).

Example 1:

Input: mat = [[1,0,0], [0,0,1], [1,0,0]] Output: 1 Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0. Example 2:

Input: mat = [[1,0,0], [0,1,0], [0,0,1]] Output: 3 Explanation: (0,0), (1,1) and (2,2) are special positions. Example 3:

Input: mat = [[0,0,0,1], [1,0,0,0], [0,1,1,0], [0,0,0,0]] Output: 2 Example 4:

Input: mat = [[0,0,0,0,0], [1,0,0,0,0], [0,1,0,0,0], [0,0,1,0,0], [0,0,0,1,1]] Output: 3

Constraints:

rows == mat.length cols == mat[i].length 1 <= rows, cols <= 100 mat[i][j] is 0 or 1.

public class Solution {
 public int NumSpecial(int[][] mat) {
 int m = mat.Length;
 int n = mat[0].Length;
 int res = 0;
 var col = new int[n];
 var row = new int[m];
 for (int i = 0; i < m; i++) 
 for (int j = 0; j < n; j++) 
 if (mat[i][j] == 1){
 col[j]++;
 row[i]++;
 } 
 for (int i = 0; i < m; i++) 
 for (int j = 0; j < n; j++) 
 if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) res++;
 return res;
 }
 
 
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 27 September 2020 · 1 min read · 237 words

Part of AskGif Blog · coding

You might also like