ADVANCED DATA STRUCTURES PROGRAM • LEVEL 10 — SPARSE MATRICES

Reconstruct a Dense Matrix from Triplets

Learn how to reconstruct a dense matrix from triplets using a clear C program.

IntermediateSparse representationTriplet form

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 5 0
2 0 7

COMPLETE C PROGRAM

Complete C implementation

ads-triplet-to-dense-matrix.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int triplets[][3] = {{0, 1, 5}, {1, 0, 2}, {1, 2, 7}};
    int matrix[2][3] = {{0}};
    for (int index = 0; index < 3; index++) matrix[triplets[index][0]][triplets[index][1]] = triplets[index][2];
    for (int row = 0; row < 2; row++)
        for (int column = 0; column < 3; column++) printf("%d%c", matrix[row][column], column == 2 ? '\n' : ' ');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0 5 0
2 0 7
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Initialize zeros and place every triplet value at its stored coordinates.
  3. Display the computed result.

Initialize zeros and place every triplet value at its stored coordinates.

EFFICIENCY

Time and space complexity

Time complexity

O(rows * 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.