Special positions in Matrix (linear-time)
Here is a problem that can be solved in linear-time: https://leetcode.com/problems/special-positions-in-a-binary-matrix/
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]
is0
or1
.
The limits are small enough that one could go for N^2, but the linear solution can be accomplished with the use of dictionaries:
- Have two dictionaries, one for rows, one for cols
- Keep track of the number of 1s in each of these dictionaries, accordingly
- In the second loop then (hence (2n)), check these dictionaries looking for "one" only
Code is below, cheers, ACC.
def numSpecial(self, mat): """ :type mat: List[List[int]] :rtype: int """ colsDict = dict() rowsDict = dict() for r in range(len(mat)): for c in range(len(mat[r])): if mat[r][c] == 1: if colsDict.get(c) == None: colsDict[c] = 1 else: colsDict[c] = colsDict[c] + 1 if rowsDict.get(r) == None: rowsDict[r] = 1 else: rowsDict[r] = rowsDict[r] + 1 retVal = 0 for r in range(len(mat)): for c in range(len(mat[r])): if mat[r][c] == 1 and colsDict[c] == 1 and rowsDict[r] == 1: retVal += 1 return retVal
Comments
Post a Comment