call(back)
Algorithms & Data Structuresmedium

Sparse Matrix Storage, Addition, and Multiplication

Matrices in Pinterest's recommender pipelines are enormous but almost entirely zeros. Design a SparseMatrix class whose storage is proportional to the number of nonzero entries, supporting:

SparseMatrix.fromDense(rows)     // build from a dense array of arrays
m.get(r, c) / m.set(r, c, v)
a.add(b)                         // -> new SparseMatrix
a.multiply(b)                    // -> new SparseMatrix
m.toDense()
m.nnz()                          // number of stored nonzero entries

Addition and multiplication must exploit sparsity — never iterate the full dense dimensions. Entries that become zero (including by cancellation in add) must be removed from storage: nnz() is how the judge checks you. Dimension mismatches in add or multiply must throw.

Asked at