The Wayback Machine - https://web.archive.org/web/20240918024517/https://www.geeksforgeeks.org/sparse-matrix-representation/
Open In App

Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)

Last Updated : 12 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix.

Why to use Sparse Matrix instead of simple matrix ?

  • Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements.
  • Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements..

Example: 

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

Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value). 

Sparse Matrix Representations can be done in many ways following are two common representations: 

  1. Array representation
  2. Linked list representation

Method 1: Using Arrays:

2D array is used to represent a sparse matrix in which there are three rows named as 

  • Row: Index of row, where non-zero element is located
  • Column: Index of column, where non-zero element is located
  • Value: Value of the non zero element located at index – (row,column)

Sparse Matrix Array Representation

Implementation:

C++




// C++ program for Sparse Matrix Representation
// using Array
#include <iostream>
using namespace std;
 
int main()
{
    // Assume 4x5 sparse matrix
    int sparseMatrix[4][5] =
    {
        {0 , 0 , 3 , 0 , 4 },
        {0 , 0 , 5 , 7 , 0 },
        {0 , 0 , 0 , 0 , 0 },
        {0 , 2 , 6 , 0 , 0 }
    };
 
    int size = 0;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
            if (sparseMatrix[i][j] != 0)
                size++;
 
    // number of columns in compactMatrix (size) must be
    // equal to number of non - zero elements in
    // sparseMatrix
    int compactMatrix[3][size];
 
    // Making of new matrix
    int k = 0;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
            if (sparseMatrix[i][j] != 0)
            {
                compactMatrix[0][k] = i;
                compactMatrix[1][k] = j;
                compactMatrix[2][k] = sparseMatrix[i][j];
                k++;
            }
 
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<size; j++)
            cout <<" "<< compactMatrix[i][j];
 
        cout <<"\n";
    }
    return 0;
}
 
// this code is contributed by shivanisinghss2110


C




// C++ program for Sparse Matrix Representation
// using Array
#include<stdio.h>
 
int main()
{
    // Assume 4x5 sparse matrix
    int sparseMatrix[4][5] =
    {
        {0 , 0 , 3 , 0 , 4 },
        {0 , 0 , 5 , 7 , 0 },
        {0 , 0 , 0 , 0 , 0 },
        {0 , 2 , 6 , 0 , 0 }
    };
 
    int size = 0;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
            if (sparseMatrix[i][j] != 0)
                size++;
 
    // number of columns in compactMatrix (size) must be
    // equal to number of non - zero elements in
    // sparseMatrix
    int compactMatrix[3][size];
 
    // Making of new matrix
    int k = 0;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
            if (sparseMatrix[i][j] != 0)
            {
                compactMatrix[0][k] = i;
                compactMatrix[1][k] = j;
                compactMatrix[2][k] = sparseMatrix[i][j];
                k++;
            }
 
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<size; j++)
            printf("%d ", compactMatrix[i][j]);
 
        printf("\n");
    }
    return 0;
}


Java




// Java program for Sparse Matrix Representation
// using Array
class GFG
{
 
    public static void main(String[] args)
    {
        int sparseMatrix[][]
                = {
                    {0, 0, 3, 0, 4},
                    {0, 0, 5, 7, 0},
                    {0, 0, 0, 0, 0},
                    {0, 2, 6, 0, 0}
                };
 
        int size = 0;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                if (sparseMatrix[i][j] != 0)
                {
                    size++;
                }
            }
        }
 
        // number of columns in compactMatrix (size) must be
        // equal to number of non - zero elements in
        // sparseMatrix
        int compactMatrix[][] = new int[3][size];
 
        // Making of new matrix
        int k = 0;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                if (sparseMatrix[i][j] != 0)
                {
                    compactMatrix[0][k] = i;
                    compactMatrix[1][k] = j;
                    compactMatrix[2][k] = sparseMatrix[i][j];
                    k++;
                }
            }
        }
 
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < size; j++)
            {
                System.out.printf("%d ", compactMatrix[i][j]);
            }
            System.out.printf("\n");
        }
    }
}
 
/* This code contributed by PrinciRaj1992 */


Python3




# Python program for Sparse Matrix Representation
# using arrays
 
# assume a sparse matrix of order 4*5
# let assume another matrix compactMatrix
# now store the value,row,column of arr1 in sparse matrix compactMatrix
 
sparseMatrix = [[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,0]]
 
# initialize size as 0
size = 0
 
for i in range(4):
    for j in range(5):
        if (sparseMatrix[i][j] != 0):
            size += 1
 
# number of columns in compactMatrix(size) should
# be equal to number of non-zero elements in sparseMatrix
rows, cols = (3, size)
compactMatrix = [[0 for i in range(cols)] for j in range(rows)]
 
k = 0
for i in range(4):
    for j in range(5):
        if (sparseMatrix[i][j] != 0):
            compactMatrix[0][k] = i
            compactMatrix[1][k] = j
            compactMatrix[2][k] = sparseMatrix[i][j]
            k += 1
 
for i in compactMatrix:
    print(i)
 
# This code is contributed by MRINALWALIA


C#




// C# program for Sparse Matrix Representation
// using Array
 
using System;
 
class Program {
    static void Main(string[] args)
    {
        // Assume 4x5 sparse matrix
        int[, ] sparseMatrix
            = new int[4, 5] { { 0, 0, 3, 0, 4 },
                              { 0, 0, 5, 7, 0 },
                              { 0, 0, 0, 0, 0 },
                              { 0, 2, 6, 0, 0 } };
        int size = 0;
        for (int i = 0; i < 4; i++)
            for (int j = 0; j < 5; j++)
                if (sparseMatrix[i, j] != 0)
                    size++;
 
        // number of columns in compactMatrix (size) must be
        // equal to number of non - zero elements in
        // sparseMatrix
        int[, ] compactMatrix = new int[3, size];
 
        // Making of new matrix
        int k = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 5; j++)
                if (sparseMatrix[i, j] != 0) {
                    compactMatrix[0, k] = i;
                    compactMatrix[1, k] = j;
                    compactMatrix[2, k]
                        = sparseMatrix[i, j];
                    k++;
                }
        }
 
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < size; j++)
                Console.Write(" " + compactMatrix[i, j]);
            Console.WriteLine();
        }
    }
}
// This code is contributed by Tapesh(tapeshdua420)


Javascript




//JS  program for Sparse Matrix Representation
// using Array
 
    // Assume 4x5 sparse matrix
    let sparseMatrix =
    [
        [0 , 0 , 3 , 0 , 4 ],
        [0 , 0 , 5 , 7 , 0 ],
        [0 , 0 , 0 , 0 , 0 ],
        [0 , 2 , 6 , 0 , 0 ]
    ];
 
    let size = 0;
    for (let i = 0; i < 4; i++)
        for (let j = 0; j < 5; j++)
            if (sparseMatrix[i][j] != 0)
                size++;
 
    // number of columns in compactMatrix (size) must be
    // equal to number of non - zero elements in
    // sparseMatrix
    let compactMatrix = new Array(3);
    for (var i = 0; i < 3; i++)
        compactMatrix[i] = new Array(size);
 
 
    // Making of new matrix
    let k = 0;
    for (let i = 0; i < 4; i++)
        for (let j = 0; j < 5; j++)
            if (sparseMatrix[i][j] != 0)
            {
                compactMatrix[0][k] = i;
                compactMatrix[1][k] = j;
                compactMatrix[2][k] = sparseMatrix[i][j];
                k++;
            }
 
    for (let i=0; i<3; i++)
    {
        for (let j=0; j<size; j++)
            process.stdout.write(" " + compactMatrix[i][j]);
 
        console.log()
    }
 
 
// this code is contributed by phasing17


Output

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

Time Complexity:  O(NM), where N is the number of rows in the sparse matrix, and M is the number of columns in the sparse matrix.

Auxiliary Space: O(NM), where N is the number of rows in the sparse matrix, and M is the number of columns in the sparse matrix.

Method 2: Using Linked Lists
In linked list, each node has four fields. These four fields are defined as: 

  • Row: Index of row, where non-zero element is located
  • Column: Index of column, where non-zero element is located
  • Value: Value of the non zero element located at index – (row,column)
  • Next node: Address of the next node

Sparse-Matrix-Linked-List 2

C++




// C++ program for sparse matrix representation.
// Using Link list
#include<iostream>
using namespace std;
 
// Node class to represent link list
class Node
{
    public:
    int row;
    int col;
    int data;
    Node *next;
};
 
// Function to create new node
void create_new_node(Node **p, int row_index,
                     int col_index, int x)
{
    Node *temp = *p;
    Node *r;
     
    // If link list is empty then
    // create first node and assign value.
    if (temp == NULL)
    {
        temp = new Node();
        temp->row = row_index;
        temp->col = col_index;
        temp->data = x;
        temp->next = NULL;
        *p = temp;
    }
     
    // If link list is already created
    // then append newly created node
    else
    {
        while (temp->next != NULL)  
            temp = temp->next;
             
        r = new Node();
        r->row = row_index;
        r->col = col_index;
        r->data = x;
        r->next = NULL;
        temp->next = r;
    }
}
 
// Function prints contents of linked list
// starting from start
void printList(Node *start)
{
    Node *ptr = start;
    cout << "row_position:";
    while (ptr != NULL)
    {
        cout << ptr->row << " ";
        ptr = ptr->next;
    }
    cout << endl;
    cout << "column_position:";
 
    ptr = start;
    while (ptr != NULL)
    {
        cout << ptr->col << " ";
        ptr = ptr->next;
    }
    cout << endl;
    cout << "Value:";
    ptr = start;
     
    while (ptr != NULL)
    {
        cout << ptr->data << " ";
        ptr = ptr->next;
    }
}
 
// Driver Code
int main()
{
     
    // 4x5 sparse matrix
    int sparseMatrix[4][5] = { { 0 , 0 , 3 , 0 , 4 },
                               { 0 , 0 , 5 , 7 , 0 },
                               { 0 , 0 , 0 , 0 , 0 },
                               { 0 , 2 , 6 , 0 , 0 } };
     
    // Creating head/first node of list as NULL
    Node *first = NULL;
    for(int i = 0; i < 4; i++)
    {
        for(int j = 0; j < 5; j++)
        {
             
            // Pass only those values which
            // are non - zero
            if (sparseMatrix[i][j] != 0)
                create_new_node(&first;, i, j,
                                sparseMatrix[i][j]);
        }
    }
    printList(first);
 
    return 0;
}
 
// This code is contributed by ronaksuba


C




// C program for Sparse Matrix Representation
// using Linked Lists
#include<stdio.h>
#include<stdlib.h>
 
// Node to represent sparse matrix
struct Node
{
    int value;
    int row_position;
    int column_postion;
    struct Node *next;
};
 
// Function to create new node
void create_new_node(struct Node** start, int non_zero_element,
                     int row_index, int column_index )
{
    struct Node *temp, *r;
    temp = *start;
    if (temp == NULL)
    {
        // Create new node dynamically
        temp = (struct Node *) malloc (sizeof(struct Node));
        temp->value = non_zero_element;
        temp->row_position = row_index;
        temp->column_postion = column_index;
        temp->next = NULL;
        *start = temp;
 
    }
    else
    {
        while (temp->next != NULL)
            temp = temp->next;
 
        // Create new node dynamically
        r = (struct Node *) malloc (sizeof(struct Node));
        r->value = non_zero_element;
        r->row_position = row_index;
        r->column_postion = column_index;
        r->next = NULL;
        temp->next = r;
 
    }
}
 
// This function prints contents of linked list
// starting from start
void PrintList(struct Node* start)
{
    struct Node *temp, *r, *s;
    temp = r = s = start;
 
    printf("row_position: ");
    while(temp != NULL)
    {
 
        printf("%d ", temp->row_position);
        temp = temp->next;
    }
    printf("\n");
 
    printf("column_postion: ");
    while(r != NULL)
    {
        printf("%d ", r->column_postion);
        r = r->next;
    }
    printf("\n");
    printf("Value: ");
    while(s != NULL)
    {
        printf("%d ", s->value);
        s = s->next;
    }
    printf("\n");
}
 
 
// Driver of the program
int main()
{
   // Assume 4x5 sparse matrix
    int sparseMatric[4][5] =
    {
        {0 , 0 , 3 , 0 , 4 },
        {0 , 0 , 5 , 7 , 0 },
        {0 , 0 , 0 , 0 , 0 },
        {0 , 2 , 6 , 0 , 0 }
    };
 
    /* Start with the empty list */
    struct Node* start = NULL;
 
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
 
            // Pass only those values which are non - zero
            if (sparseMatric[i][j] != 0)
                create_new_node(&start;, sparseMatric[i][j], i, j);
 
    PrintList(start);
 
    return 0;
}


Java




// Java program for sparse matrix representation.
// Using Link list
import java.util.*;
 
public class SparseMatrix {
    // Creating head/first node of list as NULL
    static Node first = null;
 
    // Node class to represent link list
    public static class Node {
        int row;
        int col;
        int data;
        Node next;
    };
 
    // Driver Code
    public static void main(String[] args)
    {
        // 4x5 sparse matrix
        int[][] sparseMatrix = { { 0, 0, 3, 0, 4 },
                                 { 0, 0, 5, 7, 0 },
                                 { 0, 0, 0, 0, 0 },
                                 { 0, 2, 6, 0, 0 } };
 
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 5; j++) {
                // Pass only those values which
                // are non - zero
                if (sparseMatrix[i][j] != 0) {
                    create_new_node(i, j,
                                    sparseMatrix[i][j]);
                }
            }
        }
        printList(first);
    }
    // Function to create new node
    private static void
    create_new_node(int row_index, int col_index, int x)
    {
        Node temp = first;
        Node r;
 
        // If link list is empty then
        // create first node and assign value.
        if (temp == null) {
            temp = new Node();
            temp.row = row_index;
            temp.col = col_index;
            temp.data = x;
            temp.next = null;
            first = temp;
        }
 
        // If link list is already created
        // then append newly created node
        else {
            while (temp.next != null)
                temp = temp.next;
 
            r = new Node();
            r.row = row_index;
            r.col = col_index;
            r.data = x;
            r.next = null;
            temp.next = r;
        }
    }
 
    // Function prints contents of linked list
    // starting from start
    public static void printList(Node start)
    {
        Node ptr = start;
        System.out.print("row_position:");
        while (ptr != null) {
            System.out.print(ptr.row + " ");
            ptr = ptr.next;
        }
        System.out.println("");
        System.out.print("column_position:");
 
        ptr = start;
        while (ptr != null) {
            System.out.print(ptr.col + " ");
            ptr = ptr.next;
        }
        System.out.println("");
        System.out.print("Value:");
        ptr = start;
 
        while (ptr != null) {
            System.out.print(ptr.data + " ");
            ptr = ptr.next;
        }
    }
}
 
// This code is contributed by Tapesh (tapeshdua420)


Python3




# Python Program for Representation of
# Sparse Matrix using Linked List
 
# Node Class to represent Linked List Node
class Node:
 
    # Making the slots for storing row,
    # column, value, and address
    __slots__ = "row", "col", "data", "next"
 
    # Constructor to initialize the values
    def __init__(self, row=0, col=0, data=0, next=None):
 
        self.row = row
        self.col = col
        self.data = data
        self.next = next
 
 
# Class to convert Sparse Matrix
# into Linked List
class Sparse:
 
    # Initialize Class Variables
    def __init__(self):
        self.head = None
        self.temp = None
        self.size = 0
 
    # Function which returns the size
    # of the Linked List
    def __len__(self):
        return self.size
 
    # Check the Linked List is
    # Empty or not
    def isempty(self):
        return self.size == 0
 
    # Responsible function to create
    # Linked List from Sparse Matrix
    def create_new_node(self, row, col, data):
 
        # Creating New Node
        newNode = Node(row, col, data, None)
 
        # Check whether the List is
        # empty or not
        if self.isempty():
            self.head = newNode
        else:
            self.temp.next = newNode
        self.temp = newNode
 
        # Incrementing the size
        self.size += 1
 
    # Function display the contents of
    # Linked List
    def PrintList(self):
        temp = r = s = self.head
        print("row_position:", end=" ")
        while temp != None:
            print(temp.row, end=" ")
            temp = temp.next
        print()
        print("column_postion:", end=" ")
        while r != None:
            print(r.col, end=" ")
            r = r.next
        print()
        print("Value:", end=" ")
        while s != None:
            print(s.data, end=" ")
            s = s.next
        print()
 
# Driver Code
if __name__ == "__main__":
 
    # Creating Object
    s = Sparse()
 
    # Assuming 4x5 Sparse Matrix
    sparseMatric = [[0, 0, 3, 0, 4],
                    [0, 0, 5, 7, 0],
                    [0, 0, 0, 0, 0],
                    [0, 2, 6, 0, 0]]
    for i in range(4):
        for j in range(5):
 
            # Creating Linked List by only those
            # elements which are non-zero
            if sparseMatric[i][j] != 0:
                s.create_new_node(i, j, sparseMatric[i][j])
 
    # Printing the Linked List Representation
    # of the sparse matrix
    s.PrintList()
 
    # This code is contributed by Naveen Rathore


C#




// C# program for sparse matrix representation.
// Using Link list
using System;
 
class Program
{
   
    // Creating head/first node of list as NULL
    static Node first = null;
 
    // Node class to represent link list
    public class Node {
        public int row;
        public int col;
        public int data;
        public Node next;
    };
 
    // Driver Code
    static void Main(string[] args)
    {
        // 4x5 sparse matrix
        int[, ] sparseMatrix = { { 0, 0, 3, 0, 4 },
                                 { 0, 0, 5, 7, 0 },
                                 { 0, 0, 0, 0, 0 },
                                 { 0, 2, 6, 0, 0 } };
 
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 5; j++) {
                // Pass only those values which
                // are non - zero
                if (sparseMatrix[i, j] != 0) {
                    create_new_node(i, j,
                                    sparseMatrix[i, j]);
                }
            }
        }
        printList(first);
    }
 
    // Function to create new node
    private static void
    create_new_node(int row_index, int col_index, int x)
    {
        Node temp = first;
        Node r;
 
        // If link list is empty then
        // create first node and assign value.
        if (temp == null) {
            temp = new Node();
            temp.row = row_index;
            temp.col = col_index;
            temp.data = x;
            temp.next = null;
            first = temp;
        }
 
        // If link list is already created
        // then append newly created node
        else
 
        {
            while (temp.next != null)
                temp = temp.next;
 
            r = new Node();
            r.row = row_index;
            r.col = col_index;
            r.data = x;
            r.next = null;
            temp.next = r;
        }
    }
 
    // Function prints contents of linked list
    // starting from start
    public static void printList(Node start)
    {
        Node ptr = start;
        Console.Write("row_position:");
        while (ptr != null) {
            Console.Write(ptr.row + " ");
            ptr = ptr.next;
        }
        Console.WriteLine("");
        Console.Write("column_position:");
        ptr = start;
        while (ptr != null) {
            Console.Write(ptr.col + " ");
            ptr = ptr.next;
        }
        Console.WriteLine("");
        Console.Write("Value:");
        ptr = start;
        while (ptr != null) {
            Console.Write(ptr.data + " ");
            ptr = ptr.next;
        }
    }
}
 
// This code is contributed by Tapesh (tapeshdua420)


Javascript




// JS Program for Representation of
// Sparse Matrix into Linked List
 
// Node Class to represent Linked List Node
class Node
{
    constructor(row, col, data)
    {
        this.row = row;
        this.col = col;
        this.data = data;
        this.next = null;
    }
}
 
// Class to convert Sparse Matrix
// into Linked List
class Sparse
{
 
    // Initialize Class Variables
    constructor()
    {
        this.head = null
        this.temp = null
        this.size = 0
    }
 
    // Function which returns the size
    // of the Linked List
    len()
    {
        return this.size
    }
 
    // Check the Linked List is
    // Empty or not
    isempty()
    {
        return this.size == 0
    }
 
    // Responsible function to create
    // Linked List from Sparse Matrix
    create_new_node(row, col, data)
    {
        // Creating New Node
        let newNode = new Node(row, col, data)
 
        // Check whether the List is
        // empty or not
        if (this.isempty())
            this.head = newNode
        else
            (this.temp).next = newNode
        this.temp = newNode
 
        // Incrementing the size
        this.size += 1
    }
 
    // Function display the contents of
    // Linked List
    PrintList()
    {
        let temp = this.head
        let r = this.head
        let s = this.head
         
        process.stdout.write("row_position: ")
        while (temp != null)
        {
            process.stdout.write(temp.row + " ")
            temp = temp.next
        }
        console.log()
        process.stdout.write("column_postion: ")
        while (r != null)
        {
            process.stdout.write(r.col + " " )
            r = r.next
        }
        console.log()
        process.stdout.write("Value: ")
        while (s != null)
        {
            process.stdout.write(s.data + " ")
            s = s.next
        }
        console.log()
    }
}
 
// Driver Code
 
// Creating Object
let s = new Sparse()
 
// Assuming 4x5 Sparse Matrix
let sparseMatric = [[0, 0, 3, 0, 4],
                    [0, 0, 5, 7, 0],
                    [0, 0, 0, 0, 0],
                    [0, 2, 6, 0, 0]]
 
for (var i = 0; i < 4; i++)
    for (var j = 0; j < 5; j++)
        // Creating Linked List by only those
        // elements which are non-zero
        if (sparseMatric[i][j] != 0)
        {
            s.create_new_node(i, j, sparseMatric[i][j])
            s.data = sparseMatric[i][j]
        }
             
 
 
             
 
// Printing the Linked List Representation
// of the sparse matrix
s.PrintList()


Output

row_position:0 0 1 1 3 3 
column_position:2 4 2 3 1 2 
Value:3 4 5 7 2 6 

Time Complexity:  O(N*M), where N is the number of rows in the sparse matrix, and M is the number of columns in the sparse matrix.
Auxiliary Space: O(K), where K is the number of non-zero elements in the array.

Other representations: 

As a Dictionary where row and column numbers are used as keys and values are matrix entries. This method saves space but sequential access of items is costly.

As a list of list. The idea is to make a list of rows and every item of list contains values. We can keep list items sorted by column numbers.
Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)



Similar Reads

Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)
Prerequisite : Sparse Matrix and its representations Set 1 (Using Arrays and Linked Lists)In this post other two methods of sparse matrix representation are discussed. List of ListsDictionary List of Lists (LIL) One of the possible representation of sparse matrix is List of Lists (LIL). Where one list is used to represent the rows and each row cont
15+ min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
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) ?
15+ min read
Sparse Matrix Representations | Set 3 ( CSR )
If most of the elements in the matrix are zero then the matrix is called a sparse matrix. It is wasteful to store the zero elements in the matrix since they do not affect the results of our computation. This is why we implement these matrices in more efficient representations than the standard 2D Array. Using more efficient representations we can c
11 min read
Graph and its representations
What is Graph Data Structure?A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E). Repr
3 min read
Graph representations using set and hash
We have introduced Graph implementation using array of vectors in Graph implementation using STL for competitive programming | Set 1. In this post, a different implementation is used which can be used to implement graphs using sets. The implementation is for adjacency list representation of graph. A set is different from a vector in two ways: it st
15+ min read
LCA for general or n-ary trees (Sparse Matrix DP approach )
In previous posts, we have discussed how to calculate the Lowest Common Ancestor (LCA) for a binary tree and a binary search tree (this, this and this). Now let’s look at a method that can calculate LCA for any tree (not only for binary tree). We use Dynamic Programming with Sparse Matrix Approach in our method. This method is very handy and fast w
15+ min read
Check if a given matrix is sparse or not
A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix, Examples: Input : 1 0 3 0 0 4
5 min read
Javascript Program to Check if a given matrix is sparse or not
A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix, Examples: Input : 1 0 3 0 0 4
2 min read
Product of count of set bits present in binary representations of elements in an array
Given an array arr[] consisting of N integers, the task is to find the product of the count of set bits in the binary representation of every array element. Examples: Input: arr[] = {3, 2, 4, 1, 5}Output: 4Explanation:Binary representation of the array elements are {3, 2, 4, 1, 5} are {"11", "10", "100", "1", "101"} respectively.Therefore, the prod
6 min read
Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
Why is Quick Sort preferred for arrays? Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays. Recursive Quick Sort for array. Iterative Quick Sort for arrays. Recursive Merge Sort for arrays Iterative Merge Sort for arrays Quick Sort in its general form is an in-place sort (i.e. it doesn't require any extra stor
5 min read
Sparse Set
How to do the following operations efficiently if there are large number of queries for them. InsertionDeletionSearchingClearing/Removing all the elements. One solution is to use a Self-Balancing Binary Search Tree like Red-Black Tree, AVL Tree, etc. Time complexity of this solution for insertion, deletion and searching is O(Log n).We can also use
15+ min read
Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations
Given an array arr[] consisting of N positive integers, the task is to find the maximum absolute difference between the sum of the array elements placed at even and odd indices of the array by swapping unequal adjacent bits of in the binary representation of any array element any number of times. Examples: Input: arr[] = {5, 7, 3, 1, 8}Output: 9Exp
12 min read
Maximize difference between odd and even-indexed array elements by rotating their binary representations
Given an array arr[] consisting of N positive integers, the task is to find the maximum absolute difference between the sum of the array elements placed at even indices and those at odd indices of the array by rotating their binary representations any number of times. Consider only 8-bit representation. Examples: Input: arr[] = {123, 86, 234, 189}O
12 min read
XOR of two numbers after making length of their binary representations equal
Given two numbers say a and b. Print their XOR after making the lengths of their binary representation equal by adding trailing zeros to the binary representation of smaller one. Examples : Input : a = 13, b = 5 Output : 7 Explanation : Binary representation of 13 is 1101 and of 5 is 101. As the length of "101" is smaller, so add a '0' to it making
7 min read
Digits whose alphabetic representations are jumbled in a given string
Given a string S of length N which is the English representation of any number of digits in the range [0 - 9] in jumbled format. The task is to find the digits from this representation. Note: Print digits in any order Examples Input: S = "owoftnuoer"Output: 124Explanation: The digits here are jumbled form of one, two and four. Therefore, the requir
8 min read
Check if binary representations of 0 to N are present as substrings in given binary string
Give binary string str and an integer N, the task is to check if the substrings of the string contain all binary representations of non-negative integers less than or equal to the given integer N. Examples: Input: str = “0110", N = 3 Output: True Explanation: Since substrings “0", “1", “10", and “11" can be formed from given string. Hence all binar
9 min read
Find the number obtained by concatenating binary representations of all numbers up to N
Given an integer N, the task is to find the decimal value of the binary string formed by concatenating the binary representations of all numbers from 1 to N sequentially. Examples: Input: N = 12Output: 118505380540Explanation: The concatenation results in "1101110010111011110001001101010111100". The equivalent decimal value is 118505380540. Input:
5 min read
Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted
Given an array arr[] consisting of N positive integers, the task is to rearrange the array such that the reversed binary representation of all the array elements is sorted. If the decimal equivalent of reversed binary representations of two or more array elements is equal, then the original value is taken into consideration while rearranging the ar
13 min read
Modify array by removing characters from their Hexadecimal representations which are present in a given string
Given an array arr[] of size N and a string S, the task is to modify given array by removing all characters from their hexadecimal representations that are present in S and then replacing the equivalent decimal element back into the array. Examples: Input: arr[] = {74, 91, 31, 122}, S = "1AB"Output: {4, 5, 15, 7}Explanation: 74 -&gt; (4A)16 -&gt; (
10 min read
Reorder characters of a string to valid English representations of digits
Given a string S of length N, consisting of lowercase characters containing reordered English representations of digits [0 - 9], the task is to print those digits in ascending order. Examples: Input: S = "fviefuro"Output: 45Explanation: The given string can be reshuffled to "fourfive", Therefore, the digits represented by the strings are 4 and 5. I
8 min read
Sum of decimals that are binary representations of first N natural numbers
Given a positive integer N, the task is to calculate the sum of all decimals which can be expressed as binary representations of first N natural numbers. Examples: Input: N = 3Output: 22Explanation:The Binary Representation of 1 is 01.The Binary Representation of 2 is 10.The Binary Representation of 3 is 11.Therefore, required sum = 01 + 10 + 11 =
9 min read
Count of Subsequences forming Palindrome with Binary representations
Given an array A[]. The task is to count the number of subsequences such that concatenation of binary representation of the numbers represents palindrome. Examples: Input: A[] = {1, 2, 3} Output: 4Explanation: Binary representation of all elements are {1, 10, 11} here the concatenation of {1, 3} =&gt; 111 makes palindrome similarly, concatenation o
10 min read
Comparing leading zeros in binary representations of two numbers
Given two integer numbers x and y. Compare and print which one of them has more leading zeros using Bitwise operation. If both the no. have the same no. of leading zeros, print "Equal".Note:- A leading zero is any 0 digit that comes before the first nonzero digit in the binary notation of the number.Examples: Input : 10, 16Output :10Explanation: If
8 min read
Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.Examples: Input : a = 8, b = 4 Output : Yes Binary representations of both numbers have same 0s and 1s. Input : a = 4, b = 5 Output : No Simple Approach: Find the Binary Representation of 'a' and 'b' using a simple decimal-to-binary r
9 min read
Range sum query using Sparse Table
We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 &lt;= L &lt;= R &lt;= n-1. Consider a situation when there are many range queries. Examples: Input : 3 7 2 5 8 9 query(0, 5) query(3, 5) query(2, 4) Output : 34 22 15Note : array is 0 based indexed and queries too. Since there are no updates/modificatio
8 min read
Range maximum query using Sparse Table
Given an array arr[], the task is to answer queries to find the maximum of all the elements in the index range arr[L...R].Examples: Input: arr[] = {6, 7, 4, 5, 1, 3}, q[][] = {{0, 5}, {3, 5}, {2, 4}} Output: 7 5 5 Input: arr[] = {3, 34, 1}, q[][] = {{1, 2}} Output: 34 Approach: A similar problem to answer range minimum queries has been discussed he
9 min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -&gt; 2 -&gt; 3 -&gt; 8 -&gt; NULL list2 = 1 -&gt; 7 -&gt; 4 -&gt; 5 -&gt; NULL Output: 5 -&gt; 7 -&gt; 4
11 min read
Javascript Program To Merge K Sorted Linked Lists Using Min Heap - Set 2
Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output. Examples: Input: k = 3, n = 4list1 = 1-&gt;3-&gt;5-&gt;7-&gt;NULLlist2 = 2-&gt;4-&gt;6-&gt;8-&gt;NULLlist3 = 0-&gt;9-&gt;10-&gt;11-&gt;NULLOutput: 0-&gt;1
5 min read
Range Minimum Query (Square Root Decomposition and Sparse Table)
We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index L (query start) to R (query end) where 0 &lt;= L &lt;= R &lt;= n-1. Consider a situation when there are many range queries. Example: Input: arr[] = {7, 2, 3, 0, 5, 10, 3, 12, 18}; query[] = [0, 4], [4, 7], [7, 8]Output: Minimum of [0, 4] is 0 Minim
15+ min read
Article Tags :
Practice Tags :