2D Matrix Flashcards
implement a class for 2D matrix (immutable) which is easy to compute sum of any rectangle region
cache sum of regions from (0, 0) to (i, j) – O(m*n)
get sum of region from (i_1, j_1) to (i_2, j_2) – O(1)
sparse matrix implementations
- Dictionary of keys (row, col) -> value
- List of Lists of tuple (col, value) – sorted by col index
- Coordinate List of tuple (row, col, value) – sorted by row, col
- Compressed Sparse Row (scipy implementation)
3 matrices
A – all non-zero values
IA – IA[0]=0, IA[i] = IA[i-1] + #non-zeros in row i-1
JA – column indices for non-zero values
sparse matrix dot product
List of lists iterate through (row_A, col_A) in A, iterate through (row_B = col_A, col_B) in B add (row_A, col_B) value into M
find the largest square with all 1s in a binary matrix
num[i, j] = min(num[i-1, j], num[i, j-1], num[i-1, j-1]) + 1 if val ==1 else 0
find the largest rectangle with all 1s in a binary matrix
sum over one row;
find the max area in a histogram
find the max area under a histogram
two pointers:
start (the start point with non-zero height in the consecutive area), end
min_height = min(min_height, height[end-1])
area = (end-start) * min_height
max_area = max(max_area, area)