How to store a Sparse Vector efficiently?
A sparse vector is a vector that has a large number of zeros so it takes unwanted space to store this 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 spare vector element(which is non-zero) and the second element will be the actual element.
Below is the implementation of the above approach:
// 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 pairs vector<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 pairs void print(vector<pair<int, int> > res) { for (auto x : res) { cout << "index: " << x.first << " -> value: " << x.second << endl; } } // Driver function int 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; } |
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
Recommended Posts:
- Sparse Table
- Sparse Search
- vector::push_back() and vector::pop_back() in C++ STL
- vector::crend() & vector::crbegin() with example
- vector :: cbegin() and vector :: cend() in C++ STL
- vector::front() and vector::back() in C++ STL
- vector::empty() and vector::size() in C++ STL
- Sparse Matrix Representations | Set 3 ( CSR )
- Operations on Sparse Matrices
- Range sum query using Sparse Table
- vector::begin() and vector::end() in C++ STL
- vector::at() and vector::swap() in C++ STL
- Generate original array from an array that store the counts of greater elements on right
- Compute maximum of the function efficiently over all sub-arrays
- Efficiently merging two sorted arrays with O(1) extra space
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



