Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 1 · syllabusAsked 1× in KTU papersLesson live

Sparse matrix — tuple representation

Most entries zero? Store only (row, col, value) triples — and transpose them fast.

Syllabus says: “Sparse matrix (Tuple representation)”

On this page · 14 sections
ormakkurippu ✎
Never-forget card

Row 0 of the triple table is the HEADER: (rows, cols, count). Transpose = SWAP row and col, then SORT by the new row.

Picture it

An attendance register where almost everyone is present: instead of writing ‘P’ 60 times you just write down who was absent — far less ink.

Write this in the exam

A sparse matrix is stored as triples <row, column, value> of its non-zero elements, in row-major order, with a header triple <rows, cols, number of non-zeros>.

What you will be able to do

  • Represent a sparse matrix in tuple (triple) form.
  • Write the transpose algorithm (KTU Nov 2025 Q10b).
  • Explain the fast transpose and compare the costs.

Definition

Definition

A sparse matrix is a matrix in which most of the elements are zero. Storing all m × n entries wastes memory and time, so we store only the non-zero elements as <row, col, value> triples. This is the tuple representation named in the syllabus (also called the triplet or 3-tuple form).

From matrix to triples

c0c1c2c3c4
r000304
r100570
r200000
r302600
A 4 × 5 matrix with 6 non-zeros.
Triples in row-major order (sorted by row, then column).
rowcolvalue
a[0] (header)456
a[1]023
a[2]044
a[3]125
a[4]137
a[5]312
a[6]326
Watch outIs it actually worth it?

Triples use 3(t + 1) numbers versus m·n for the full matrix. Here 3 × 7 = 21 > 20, so this small example does not save space! It pays off only when t < mn/3 − 1. Real sparse matrices (say 1000 × 1000 with 3000 non-zeros) save over 99%.

Worked example

Transpose of the example (5 × 4). It is sorted by the new row.
rowcolvalue
b[0]546
b[1]132
b[2]203
b[3]215
b[4]236
b[5]317
b[6]404
Fast transpose helper arrays: column 2 has 3 terms, so its block starts at 2 and the next column starts at 5.
column of a01234
rowTerms01311
startingPos11256

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Also try: Simple transpose

Algorithm: transpose

Transposing means element (i, j) moves to (j, i). Simply swapping row and col breaks the row-major order, so we produce the result column by column of the original.

algorithm
Algorithm Transpose(a, b)          // a: original triples, b: result
1. b[0].row ← a[0].col;  b[0].col ← a[0].row;  b[0].value ← a[0].value
2. if a[0].value > 0 then
3.     k ← 1
4.     for c ← 0 to a[0].col − 1 do          // for every column of a
5.         for i ← 1 to a[0].value do         // scan all terms
6.             if a[i].col = c then
7.                 b[k].row ← a[i].col;  b[k].col ← a[i].row
8.                 b[k].value ← a[i].value;  k ← k + 1
9. end

Fast transpose — O(cols + terms)

algorithm
Algorithm FastTranspose(a, b)
1. copy the header with rows and cols swapped (as above)
2. for i ← 0 to cols − 1: rowTerms[i] ← 0
3. for i ← 1 to terms: rowTerms[a[i].col] ← rowTerms[a[i].col] + 1
4. startingPos[0] ← 1
5. for i ← 1 to cols − 1: startingPos[i] ← startingPos[i−1] + rowTerms[i−1]
6. for i ← 1 to terms do
7.     j ← startingPos[a[i].col];  startingPos[a[i].col] ← j + 1
8.     b[j] ← (a[i].col, a[i].row, a[i].value)

C implementation

sparse_transpose.ctested ✓ 240/240 cases
C
/* Sparse matrix: triple representation, simple and fast transpose — KTU PCCST303, Module 1
 * a[0] = (rows, cols, t); a[1..t] = (row, col, value) in row-major order.
 * Input : S|F  rows cols  then the matrix row by row.
 * Output: "B: r c v" for b[0..t] (b[0] is the header of the transpose).                  */
#include <stdio.h>

#define MAXT 101
struct triple { int row, col, value; };

void simpleTranspose(struct triple a[], struct triple b[]) {
    int n = a[0].value, k = 1, c, i;
    b[0].row = a[0].col; b[0].col = a[0].row; b[0].value = n;
    for (c = 0; c < a[0].col; c++)            /* for every column of A ...     */
        for (i = 1; i <= n; i++)              /* ... scan all t triples: O(cols·t) */
            if (a[i].col == c) {
                b[k].row = a[i].col; b[k].col = a[i].row; b[k].value = a[i].value;
                k++;
            }
}

void fastTranspose(struct triple a[], struct triple b[]) {
    int rowTerms[MAXT] = {0}, startPos[MAXT];
    int n = a[0].value, cols = a[0].col, i, j;
    b[0].row = cols; b[0].col = a[0].row; b[0].value = n;
    if (n == 0) return;
    for (i = 1; i <= n; i++) rowTerms[a[i].col]++;               /* terms per column */
    startPos[0] = 1;
    for (i = 1; i < cols; i++) startPos[i] = startPos[i - 1] + rowTerms[i - 1];
    for (i = 1; i <= n; i++) {                                  /* place each triple directly */
        j = startPos[a[i].col]++;
        b[j].row = a[i].col; b[j].col = a[i].row; b[j].value = a[i].value;
    }
}

int main(void) {
    struct triple a[MAXT], b[MAXT];
    char algo[4];
    int rows, cols, r, c, x, t = 0, i;
    if (scanf("%3s %d %d", algo, &rows, &cols) != 3 || rows < 1 || cols < 1 || rows * cols > MAXT - 1) { printf("BAD INPUT\n"); return 1; }
    for (r = 0; r < rows; r++)
        for (c = 0; c < cols; c++) {
            if (scanf("%d", &x) != 1) { printf("BAD INPUT\n"); return 1; }
            if (x != 0) { t++; a[t].row = r; a[t].col = c; a[t].value = x; }
        }
    a[0].row = rows; a[0].col = cols; a[0].value = t;
    if (algo[0] == 'F') fastTranspose(a, b); else simpleTranspose(a, b);
    for (i = 0; i <= t; i++) printf("B: %d %d %d\n", b[i].row, b[i].col, b[i].value);
    return 0;
}
Sample run · fast transpose · real output from gcc

Input (stdin)

F 4 5
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0

Output (stdout)

B: 5 4 6
B: 1 3 2
B: 2 0 3
B: 2 1 5
B: 2 3 6
B: 3 1 7
B: 4 0 4

Open in the Code Lab →

Complexity

MethodTime
Transpose a full m × n matrixO(rows · cols)
Simple triple transposeO(cols · terms)
Fast transposeO(cols + terms)

Common mistakes

  • Forgetting to swap rows and cols in the header.
  • Just swapping row/col of each triple without re-sorting.
  • Starting the term loop at index 0 (that is the header).

Asked in KTU exams (1)

Quick check — can you get them all?

Question 1

Q1.The first row of the triple representation stores…

Question 2

Q2.The fast transpose needs which two helper arrays?

Question 3

Q3.Simple transpose (scan all terms once per column) costs…

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Triples <row, col, value>, row-major; a[0] = <rows, cols, terms>.
  • Transpose: for each column c, copy matching terms with row/col swapped → O(cols·terms).
  • Fast transpose: rowTerms + startingPos → O(cols + terms).

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — §2.5 (Sparse matrices)

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)