ADVANCED DATA STRUCTURES PROGRAM • LEVEL 10 — SPARSE MATRICES
Fast-Transpose a Sparse Matrix
Learn how to fast-transpose a sparse matrix using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 1 5 1 2 6 2 0 4 2 2 7
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int source[][3] = {{0, 2, 4}, {1, 0, 5}, {2, 1, 6}, {2, 2, 7}};
int count[3] = {0}, position[3] = {0}, result[4][3];
for (int index = 0; index < 4; index++) count[source[index][1]]++;
for (int column = 1; column < 3; column++) position[column] = position[column - 1] + count[column - 1];
for (int index = 0; index < 4; index++) {
int slot = position[source[index][1]]++;
result[slot][0] = source[index][1]; result[slot][1] = source[index][0]; result[slot][2] = source[index][2];
}
for (int index = 0; index < 4; index++) printf("%d %d %d\n", result[index][0], result[index][1], result[index][2]);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 5 1 2 6 2 0 4 2 2 7
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Count entries per destination row and use prefix positions to place each transposed triplet directly.
- Display the computed result.
Count entries per destination row and use prefix positions to place each transposed triplet directly.
EFFICIENCY
Time and space complexity
Time complexity
O(columns + non-zero)
Auxiliary space
O(non-zero elements)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
