Sparse Arrays
A sparse array stores only the entries that are actually set and treats every missing index as zero. When most positions are empty, memory and work then grow with the real data instead of with the size of the index range.
Paying for Emptiness
Sparse arrays (and sparse matrices) are arrays where nearly every entry is zero, or whatever the default value is. A normal dense array spends one slot per position, so when 99% of positions hold nothing, 99% of the memory records absence.
Real numbers make the waste plain. A 100,000 × 100,000 matrix of 8-byte doubles needs 80 GB dense. If only 0.01% of its entries are non-zero, that is a million values, or 8 MB of actual data: the dense version costs ten thousand times the information it holds.
Time is wasted too. A dense loop multiplies and adds every zero. A sparse algorithm touches only the stored entries, so its cost grows with nnz, the number of non-zeros, rather than with rows × columns.
The price is that every stored value must also carry where it belongs. A polynomial stored as a linked list is the one-dimensional case: one node per non-zero term, each holding its exponent next to its coefficient.
- Dense cost: one slot per position, zero or not
- Sparse cost: one entry per non-zero, plus its index
- nnz, the non-zero count, is the size that matters
Coordinate List and Dictionary of Keys
The coordinate list (COO) is the simplest sparse matrix representation: one (row, column, value) triple per non-zero, kept in three parallel arrays or one array of records. For a one-dimensional sparse array it is just (index, value) pairs, which is what the code builds.
Adding an entry is an O(1) append, so COO is the natural format for building a matrix piece by piece or reading one from a file; the Matrix Market file format is a list of triples. Finding one entry means scanning all of them, O(nnz). Sorting once by index allows binary search, O(log nnz), but every new entry must then be inserted in order.
A dictionary of keys (DOK) maps (row, column) to the value in a hash table. Reading, writing and deleting any entry are O(1) on average, which suits a matrix that is still changing in unpredictable places. The cost is hashing on every access, the table's own memory, and no useful order when iterating.
So the usual workflow has two phases: build in COO or DOK, then convert to CSR to compute. That is what SciPy's documentation recommends, and why scipy.sparse offers several formats instead of one.
- COO: O(1) append, O(nnz) lookup unsorted, O(log nnz) sorted
- DOK: O(1) average lookup and update, no order
- Missing index means zero, not an error
Compressed Sparse Row
Compressed sparse row (CSR) is the format numerical libraries compute with. It stores the non-zeros row by row, left to right, in two arrays of length nnz: values holds the numbers and colIndex holds each one's column. A third array, rowPtr, has rows + 1 entries: rowPtr[r] is where row r's entries start.
The compression is that third array. COO repeats a row number for every entry; CSR stores one pointer per row, because the entries are already grouped by row. Row r is exactly the slice from rowPtr[r] to rowPtr[r + 1], its entry count is the difference of the two, and the last pointer equals nnz. An empty row simply has two equal pointers.
That layout is built for matrix-vector multiplication, the core of iterative solvers: each output value is one row times the vector, and CSR hands over each row as one contiguous run. Finding a single entry means searching inside its row, O(log k) for a row of k entries, and inserting one shifts everything after it. CSC (compressed sparse column) is the same idea by column; MATLAB uses it internally.
| Format | Stores | Fast at | Slow at |
|---|---|---|---|
| COO | (row, col, value) triples | Appending, reading files | Finding one entry |
| DOK | Hash map from (row, col) | Random reads and edits | Ordered iteration |
| CSR | values, column indexes, row pointers | Reading a row, matrix-vector product | Inserting entries |
| CSC | The same, by column | Reading a column | Row operations |
- values and colIndex: one entry per non-zero
- rowPtr: rows + 1 entries; row r spans rowPtr[r] to rowPtr[r + 1]
- Adding a non-zero means shifting arrays and bumping later row pointers
Terms, operations, and practical uses
Memory concepts
- SparsityThe share of entries that are zero (or the default). High sparsity means most positions are empty.
- Default valueThe value any index not stored is assumed to hold, usually 0 or null.
- Index overheadThe indexes stored next to each value; if the data is not sparse enough, they cost more than a dense array.
Representations
- Dictionary of keysA hash map from index to value: O(1) average lookup, more memory per entry.
- Coordinate list (COO)A list of (index, value) or (row, col, value) entries: O(1) append, O(nnz) or O(log nnz) lookup.
- Compressed sparse row (CSR)values, column indexes and rows + 1 row pointers; fast row access and matrix-vector products.
Applications
- GraphsAdjacency lists store only the edges that exist, O(V + E) instead of V².
- Machine learningOne-hot and bag-of-words features, where almost every column is zero for a given row.
- Scientific computingMesh-based equations where each point touches only its neighbours.
Code in Python, C++ and Java
coo = []
coo.append((100, 5))
coo.append((999, 2))
coo.append((50, 9))
# Sort by index for binary search capabilities
coo.sort(key=lambda x: x[0])
print('Sorted COO:', coo)#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<pair<int, int>> coo;
coo.push_back({100, 5});
coo.push_back({999, 2});
coo.push_back({50, 9});
sort(coo.begin(), coo.end());
cout << "Sorted COO: [";
for (size_t i = 0; i < coo.size(); i++) {
if (i) cout << ", ";
cout << '(' << coo[i].first << ", " << coo[i].second << ')';
}
cout << "]\n";
}import java.util.*;
class Main {
static class Element implements Comparable<Element> {
int index, value;
Element(int i, int v) { index = i; value = v; }
public int compareTo(Element other) { return this.index - other.index; }
}
public static void main(String[] args) {
List<Element> coo = new ArrayList<>();
coo.add(new Element(100, 5));
coo.add(new Element(999, 2));
coo.add(new Element(50, 9));
Collections.sort(coo);
StringBuilder sb = new StringBuilder("Sorted COO: [");
for (int i = 0; i < coo.size(); i++) {
if (i > 0) sb.append(", ");
sb.append('(').append(coo.get(i).index).append(", ").append(coo.get(i).value).append(')');
}
System.out.println(sb.append("]"));
}
}Step through it
Running on set a[100] = 5, a[999] = 2, a[50] = 9; then a 4 × 5 matrix with 5 non-zeros
When Sparse Pays Off
Each stored entry costs more than a dense slot. With 8-byte values and 4-byte indexes, a COO entry for a matrix takes 16 bytes against 8 dense, so it only saves memory below 50% density; CSR takes about 12 bytes per entry, breaking even near two thirds.
Speed breaks even much lower, because a sparse loop reads indexes and jumps around while a dense loop streams memory. A common rule of thumb is that sparse formats start to win on speed below about 10% density and win hugely below 1%. Between those, measure.
Sparse data is the normal case in several big areas. A graph's adjacency list is a sparse format, which is why it beats the V × V matrix for most graphs. The Netflix Prize ratings filled about 1.2% of the user-by-movie grid. scikit-learn's text vectorisers return sparse matrices, since each document uses a tiny part of the vocabulary. Physics simulations on a mesh give matrices where each row has a handful of non-zeros among millions of columns.
Two names cause confusion. A sparse table is a range-minimum structure and has nothing to do with sparse storage. And HackerRank's 'Sparse Arrays' exercise is a string-counting task: count how often each query string appears in a list. A hash map from string to count solves it in O(n + q).
- Memory break-even: about 50% density for COO, about 67% for CSR
- Speed break-even: usually somewhere below 10%
- Estimate the density before choosing a format