Sparse Array Implementation

You have a large array with most of the elements as zero.

Use a more space-efficient data structure, SparseArray, that implements the same interface:

  • init(arr, size): initialize with the original large array and size.
  • set(i, val): updates index at i with val.
  • get(i): gets the value at index i.

Example:

Input:  arr[]={2, 1, 0, 0, 0, 4, 5, 3, 0, 0, 0, 2}
Output: 0 0 12 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

map<intintspcarr;
void SparseArray(vector<intarrint size)
{
    for (int i = 0i < sizei++)
    {
        if (arr[i])
            spcarr[i] = arr[i];
    }
}

void set1(int iint val)
{
    spcarr[i] = val;
}

int get(int i)
{
    if (spcarr.find(i!= spcarr.end())
        return spcarr[i];
    return 0;
}

int main()
{
    vector<intarr = {210004530002};
    SparseArray(arrarr.size());
    cout << get(4<< " ";
    cout << get(3<< " ";
    set1(312);
    cout << get(3<< " ";
    return 0;
}


No comments:

Post a Comment