CODEBHAVYA โ€ข ADS LEVEL 10

๐Ÿงฎ Sparse Matrices

Represent matrices containing mostly zero values efficiently using triplet, CSR and CSC formats, then perform transpose, addition and multiplication without wasting storage.

๐ŸŽฏ Learning Objectives

After completing this level, you should be able to:

  • Identify when a matrix should be treated as sparse.
  • Compare dense storage with triplet, CSR and CSC representations.
  • Construct row pointers and column pointers correctly.
  • Transpose a sparse matrix using the simple and fast methods.
  • Add compatible sparse matrices by merging ordered terms.
  • Explain sparse-matrix multiplication and its practical uses.
  • Analyze storage requirements and operation complexity.

๐Ÿงญ 1. What Is a Sparse Matrix?

A matrix is called sparse when most of its elements are zero. Instead of storing every zero, a sparse representation stores only the non-zero values and enough position information to reconstruct the matrix.

Density: nnz รท (rows ร— columns). Sparsity: 1 โˆ’ density, where nnz is the number of non-zero terms.
00500 80070 06000 00009
Example: The 4 ร— 5 matrix above has 20 positions but only 5 non-zero terms. Its density is 25% and its sparsity is 75%.

๐Ÿ’พ 2. Dense and Sparse Storage Comparison

Dense Representation

Stores rows ร— columns values, including every zero.

Storage: ฮ˜(mn)

Sparse Representation

Stores only nnz values plus row/column metadata.

Storage: ฮ˜(nnz + m + n)
SituationSuitable ChoiceReason
Most values are non-zeroDense arrayDirect indexing with little metadata overhead
Mostly zero, row operations dominateCSREfficient row traversal and matrix-vector multiplication
Mostly zero, column operations dominateCSCEfficient column traversal
Simple storage or teachingTriplet/COOEasy to construct and understand
Important: Sparse storage is not always smaller. When nnz is large, index metadata can cost more than storing the matrix densely.

๐Ÿ“ 3. Triplet Representation (COO)

Every non-zero term is stored as (row, column, value). A header may additionally store the matrix dimensions and the number of non-zero terms.

RowColumnValueMeaning
4554 rows, 5 columns, 5 non-zero terms
025A[0][2] = 5
108A[1][0] = 8
137A[1][3] = 7
216A[2][1] = 6
349A[3][4] = 9

Advantages

  • Simple to build
  • Easy to append terms
  • Convenient intermediate format

Limitations

  • Row boundaries are not explicit
  • Searching a particular row may scan terms
  • Repeated row/column indices add overhead

โžก๏ธ 4. Compressed Sparse Row (CSR)

CSR stores non-zero terms row by row using three arrays:

values[5, 8, 7, 6, 9]

Non-zero values in row-major order.

columnIndex[2, 0, 3, 1, 4]

Column of every stored value.

rowPointer[0, 1, 3, 4, 5]

Starting offset of each row; the final entry equals nnz.

Terms in row r: indexes rowPointer[r] through rowPointer[r + 1] โˆ’ 1.

Reading Row 1

rowPointer[1] = 1 and rowPointer[2] = 3. Therefore, CSR entries 1 and 2 belong to row 1: values 8 and 7 at columns 0 and 3.

โฌ‡๏ธ 5. Compressed Sparse Column (CSC)

CSC is the column-oriented counterpart of CSR. It stores:

values[8, 6, 5, 7, 9]

Non-zero values in column-major order.

rowIndex[1, 2, 0, 1, 3]

Row of every stored value.

columnPointer[0, 1, 2, 3, 4, 5]

Starting offset of each column.

Choose CSR When

Rows are accessed repeatedly, such as sparse matrix-vector multiplication.

Choose CSC When

Columns are accessed repeatedly, such as many numerical factorization routines.

โš™๏ธ 6. Operations on Sparse Matrices

1

Access

Locate a row/column range, then search its stored indices.

O(nnz in row)
2

Transpose

Swap each termโ€™s row and column while maintaining order.

O(nnz + columns)
3

Addition

Merge two ordered term sequences and combine matching positions.

O(nnzA + nnzB)
4

Multiplication

Match non-zero entries from rows of A with compatible rows/columns of B.

Depends on structure
5

Insertion

Insert metadata while preserving sorted positions.

May shift entries
6

Matrixโ€“Vector

Multiply using only stored terms instead of every matrix cell.

O(nnz)

๐Ÿ”„ 7. Simple and Fast Transpose

The transpose Aแต€ changes an m ร— n matrix into an n ร— m matrix, with Aแต€[j][i] = A[i][j].

Simple Transpose

For each column, scan all triplet terms and copy matching entries.

O(columns ร— nnz)

Fast Transpose

Count terms per column, compute starting positions and place each term once.

O(columns + nnz)
1

Count each original column

These columns become rows in the transpose.

2

Calculate starting positions

Use prefix sums of the column counts.

3

Place every term

Swap row and column and advance that columnโ€™s next position.

โž• 8. Sparse Matrix Addition

Two matrices can be added only when they have identical dimensions. If their triplets are sorted by (row, column), addition resembles merging two sorted arrays.

1

Compare positions

Copy the term with the smaller (row, column) position.

2

Combine equal positions

Add their values; store the sum only when it is non-zero.

3

Copy remaining terms

Append any unprocessed terms from either matrix.

Cancellation: If values at the same position sum to zero, do not store that term in the result.

โœ–๏ธ 9. Sparse Matrix Multiplication

For A(m ร— n) ร— B(n ร— p), a result entry C[i][j] is formed from matching column indices of row i in A and row indices of column j in B. Efficient implementations commonly use CSR for A and CSC for B.

Main saving: zero terms never participate. Work is performed only for compatible non-zero pairs.
Practical warning: The product of two sparse matrices can become much denser. This is called fill-in and may significantly increase memory use.

๐Ÿง  10. Choosing the Correct Format

FormatBest StrengthWeaknessCommon Use
COO/TripletEasy constructionRepeated row and column indicesLoading and coordinate data
CSRFast row accessCostly structural insertionMatrix-vector multiplication
CSCFast column accessCostly structural insertionColumn-oriented numerical methods
DOK/HashFlexible updatesHigher metadata overheadBuilding a sparse matrix
INTERACTIVE ALGORITHM VISUALIZATION

๐ŸŽฌ 11. Premium Sparse Matrix Visualizer

CodeBhavya

Enter a matrix and click Analyze Matrix. The visualizer generates Triplet, CSR and CSC representations only after the button is pressed.

Choose an example or enter values, then click Analyze Matrix.

๐Ÿ’ป 12. Fast Transpose Using Triplets

The first triplet stores rows, columns and nnz. The algorithm counts original columns and uses starting positions to build an ordered transpose.

#include <stdio.h>

#define MAX_TERMS 100
#define MAX_COLS 50

typedef struct {
    int row, col, value;
} Term;

void fastTranspose(Term a[], Term b[]) {
    int rows = a[0].row;
    int cols = a[0].col;
    int terms = a[0].value;
    int count[MAX_COLS] = {0};
    int start[MAX_COLS];

    b[0] = (Term){cols, rows, terms};
    for (int i = 1; i <= terms; i++)
        count[a[i].col]++;

    start[0] = 1;
    for (int i = 1; i < cols; i++)
        start[i] = start[i - 1] + count[i - 1];

    for (int i = 1; i <= terms; i++) {
        int position = start[a[i].col]++;
        b[position] = (Term){a[i].col, a[i].row, a[i].value};
    }
}

int main(void) {
    Term a[MAX_TERMS], b[MAX_TERMS];
    scanf("%d %d %d", &a[0].row, &a[0].col, &a[0].value);
    for (int i = 1; i <= a[0].value; i++)
        scanf("%d %d %d", &a[i].row, &a[i].col, &a[i].value);

    fastTranspose(a, b);
    printf("%d %d %d\n", b[0].row, b[0].col, b[0].value);
    for (int i = 1; i <= b[0].value; i++)
        printf("%d %d %d\n", b[i].row, b[i].col, b[i].value);
    return 0;
}

Sample Input

4 5 5
0 2 5
1 0 8
1 3 7
2 1 6
3 4 9

Sample Output

5 4 5
0 1 8
1 2 6
2 0 5
3 1 7
4 3 9

๐Ÿ” 13. Program Tracing โ€” Fast Transpose

Trace column counting, starting-position calculation and placement of all five non-zero terms.

๐Ÿ“ˆ 14. Complexity Analysis

OperationTime ComplexityExtra Space
Build triplet from dense matrixO(rows ร— columns)O(nnz)
Fast transposeO(columns + nnz)O(columns + nnz)
Add ordered tripletsO(nnzA + nnzB)O(nnzResult)
CSR matrix-vector multiplicationO(nnz)O(rows) for result
CSR row traversalO(nnz in that row)O(1)
CSR storage: nnz values + nnz column indices + (rows + 1) row pointers = 2nnz + rows + 1 stored numbers.

๐Ÿ’ก 15. Important Points and Common Mistakes

โŒ Incorrect row pointer length

CSR rowPointer must contain rows + 1 entries.

โŒ Omitting the final pointer

The final pointer must equal nnz so the last row has an ending boundary.

โŒ Unsorted triplets

Addition and conversion are simpler when terms are ordered by row and column.

โŒ Storing zero results

When addition cancels values, omit the resulting zero term.

โŒ Ignoring metadata cost

Sparse formats may waste space when the matrix is not sufficiently sparse.

โŒ Assuming sparse product

Multiplication can create fill-in and a much denser result.

01

Why does CSR have rows + 1 pointers?

02

When is CSC preferable to CSR?

03

How does fast transpose improve simple transpose?

04

What is fill-in during multiplication?

โœ๏ธ 16. Practice Problems

Solve each problem first. Use Hint only when needed and Show Answer to verify your reasoning.

1. A 10 ร— 10 matrix has 12 non-zero terms. Find its density and sparsity.

2. What does the triplet (3, 5, โˆ’7) represent?

3. How many integers are stored by a triplet format with a header and 20 non-zero terms?

4. What is the required length of CSR rowPointer for a matrix with 8 rows?

5. What must the last CSR rowPointer entry equal?

6. CSR rowPointer is [0, 2, 2, 5]. How many non-zero terms are in each row?

7. Which format is generally better for repeated row traversal?

8. Which format is generally better for repeated column traversal?

9. Transpose the triplet (2, 4, 9).

10. What is the time complexity of simple triplet transpose?

11. What is the time complexity of fast transpose?

12. Can a 3 ร— 4 matrix be added to a 4 ร— 3 matrix?

13. During addition, what should happen when matching values 6 and โˆ’6 are combined?

14. Give the time for merging ordered triplets containing p and q terms.

15. How many stored numbers does CSR use for m rows and k non-zero terms?

16. Why can sparse storage be inefficient for a nearly dense matrix?

17. What is fill-in?

18. What is the time of CSR matrix-vector multiplication?

19. Which representation is usually easiest while incrementally constructing a matrix?

20. Why are triplets normally sorted by row and then column?

๐Ÿ“ 17. Quick Revision

  • A sparse matrix contains mostly zero values; nnz counts its non-zero terms.
  • Triplet/COO stores (row, column, value) for each non-zero term.
  • CSR uses values, columnIndex and rowPointer arrays.
  • CSC uses values, rowIndex and columnPointer arrays.
  • Fast transpose takes O(columns + nnz) time.
  • Ordered sparse addition merges terms in O(nnzA + nnzB) time.
  • Sparse multiplication may create fill-in and a denser result.
  • Choose a format according to access direction, update needs and actual sparsity.