How to store a Sparse Vector efficiently?

07 Jul, 2021
A sparse vector is a vector that has a large number of zeros so it takes unwanted space to store these zeroes.The task is to store a given sparse vector efficiently without storing the zeros.
Examples:  
Input: vector = { 2, 0, 0, 0, 0, 
                  3, 0, 4, 0, 0, 
                  0, 1, 5, 0, 0, 
                  0, 0, 0, 0, 0, 
                  0, 0, 4, 0, 0, 
                  0, 2, 0, 0, 0, 
                  0, 0, 0, 3, 0, 
                  0, 0, 1, 0, 0, 
                  0, 0, 5 }
Output: {2, 3, 4, 1, 5, 
        4, 2, 3, 1, 5}
Approach: To store the sparse vector efficiently, a vector of pairs can be used. The First element of pair will be the index of sparse vector element(which is non-zero) and the second element will be the actual element. 
Below is the implementation of the above approach: 
C++
Java
Python3
Javascript
// C++ program to store sparse vectors// with the help of vector of pair #include <bits/stdc++.h>using namespace std; // Store the sparse vector// as a vector of pairsvector<pair<int, int> >convertSparseVector(vector<int> v){    vector<pair<int, int> > res;    for (int i = 0; i < v.size(); i++) {        if (v[i] != 0) {            res.push_back(make_pair(i, v[i]));        }    }    return res;} // Print the vector of pairsvoid print(vector<pair<int, int> > res){     for (auto x : res) {        cout << "index: " << x.first             << " -> value: "             << x.second << endl;    }} // Driver functionint main(){     // Get the sparse vector    vector<int> v{ 2, 0, 0, 0, 0,                   3, 0, 4, 0, 0,                   0, 1, 5, 0, 0,                   0, 0, 0, 0, 0,                   0, 0, 4, 0, 0,                   0, 2, 0, 0, 0,                   0, 0, 0, 3, 0,                   0, 0, 1, 0, 0,                   0, 0, 5 };     // Get the stored vector of pairs    vector<pair<int, int> > res        = convertSparseVector(v);     // Print the vector of pairs    print(res);     return 0;}
// Java program to store sparse vectors// with the help of ArrayList of pairimport java.util.ArrayList; class GFG{ static class Pair{    int first, second;         public Pair(int first, int second)    {        this.first = first;        this.second = second;    }} // Store the sparse ArrayList// as a ArrayList of pairsstatic ArrayList<Pair> convertSparseVector(int[] v){    ArrayList<Pair> res = new ArrayList<>();    for(int i = 0; i < v.length; i++)    {        if (v[i] != 0)        {            res.add(new Pair(i, v[i]));        }    }    return res;} // Print the ArrayList of pairsstatic void print(ArrayList<Pair> res){    for(Pair x : res)    {        System.out.printf("index: %d -> value: %d\n",                          x.first, x.second);    }} // Driver codepublic static void main(String[] args){         // Get the sparse ArrayList    int[] v = { 2, 0, 0, 0, 0,                3, 0, 4, 0, 0,                0, 1, 5, 0, 0,                0, 0, 0, 0, 0,                0, 0, 4, 0, 0,                0, 2, 0, 0, 0,                0, 0, 0, 3, 0,                0, 0, 1, 0, 0,                0, 0, 5 };     // Get the stored ArrayList of pairs    ArrayList<Pair> res = convertSparseVector(v);     // Print the ArrayList of pairs    print(res);}} // This code is contributed by sanjeev2552
# Python3 program to store sparse vectors# with the help of vector of pair # Store the sparse vector# as a vector of pairsdef convertSparseVector(v):    res = []    for i in range(len(v)):        if (v[i] != 0):            res.append([i, v[i]])     return res # Print the vector of pairsdef printf(res):    for x in res:        print("index:", x[0],              " -> value:", x[1]) # Driver Codeif __name__ == '__main__':         # Get the sparse vector    v = [2, 0, 0, 0, 0,         3, 0, 4, 0, 0,         0, 1, 5, 0, 0,         0, 0, 0, 0, 0,         0, 0, 4, 0, 0,         0, 2, 0, 0, 0,         0, 0, 0, 3, 0,         0, 0, 1, 0, 0,         0, 0, 5]     # Get the stored vector of pairs    res = convertSparseVector(v)     # Print the vector of pairs    printf(res) # This code is contributed by Surendra_Gangwar
<script> // JavaScript program to store sparse vectors// with the help of vector of pair // Store the sparse vector// as a vector of pairsfunction convertSparseVector(v) {    let res = [];    for (let i = 0; i < v.length; i++) {        if (v[i] != 0) {            res.push([i, v[i]]);        }    }    return res;} // Print the vector of pairsfunction print(res) {     for (let x of res) {        document.write("index: " + x[0] + " -> value: "        + x[1] + "<br>");    }} // Driver function // Get the sparse vectorlet v = [2, 0, 0, 0, 0,    3, 0, 4, 0, 0,    0, 1, 5, 0, 0,    0, 0, 0, 0, 0,    0, 0, 4, 0, 0,    0, 2, 0, 0, 0,    0, 0, 0, 3, 0,    0, 0, 1, 0, 0,    0, 0, 5]; // Get the stored vector of pairslet res = convertSparseVector(v); // Print the vector of pairsprint(res);  // This code is contributed by _saurabh_jaiswal </script>
index: 0 -> value: 2
index: 5 -> value: 3
index: 7 -> value: 4
index: 11 -> value: 1
index: 12 -> value: 5
index: 22 -> value: 4
index: 26 -> value: 2
index: 33 -> value: 3
index: 37 -> value: 1
index: 42 -> value: 5
 
SURENDRA_GANGWAR
sanjeev2552
_saurabh_jaiswal
surindertarika1234
cpp-vector
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Next Greater Element
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Move all negative numbers to beginning and positive to end with constant extra space
Count pairs with given sum