Open In App

Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
4 Likes
Like
Report

Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix.

Examples:

Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}
Output:
Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ? (2, 2, 2) ? (1, 1, 1) ? (0, 1, 1) ? NULL
Original matrix:
{{0, 1, 0, 0, 0}, 
{0, 1, 0, 0, 0}, 
{0, 0, 2, 0, 0}, 
{0, 3, 0, 0, 4}
{0, 0, 5, 0, 0}}

Input: mat[][] = {{0, 0, 0, 4, 0}, {0, 1, 0, 0, 0}}
Output:
Linked list representation: (1, 1, 1) ? (0, 3, 4) ? NULL
Original matrix:
{{0, 0, 0, 4, 0}, 
{0, 1, 0, 0, 0}}

Approach: The given problem can be solved by storing the row index, column index, its value, and the next pointer of all non-zero elements in the node of the linked list. Follow the steps below to solve the problem: 

Below is the implementation of the above approach:

C++
C Java Python3 C# JavaScript

Output
Linked list representation:
(4, 2, 5)->(3, 4, 4)->(3, 1, 3)->(2, 2, 2)->(1, 1, 1)->(0, 1, 1)->NULL
Original Matrix Re-Construction:
0, 1, 0, 0, 0, 
0, 1, 0, 0, 0, 
0, 0, 2, 0, 0, 
0, 3, 0, 0, 4, 
0, 0, 5, 0, 0, 


Time Complexity: O(N*M) 
Auxiliary Space: O(N*M)


Article Tags :

Similar Reads