Input: arr =[0,1,0,0,2,0,0,3], size =8Output: values at indices by calling get(i) have the same values as the original array.Input: sparseArray.set(4,5)Explanation: Updates the value at index 4 to 5in the sparse array.Input: sparseArray.get(4)Output: 5Explanation: Retrieves the updated value(5) at index 4.
A sparse array contains mostly zero values. Storing zeros explicitly in an array would be very space inefficient. Instead, we can use a dictionary (hashmap) to store only the non-zero elements. This way, we only use space proportional to the number of non-zero elements.
Initialization: init(arr, size) will take the large array and its size, and store only non-zero elements in a dictionary where the key is the index and the value is the element.
Set Operation: set(i, val) will update the dictionary. If val is non-zero, it adds or updates the entry in the dictionary. If val is zero and the key exists in the dictionary, it removes the key.
Get Operation: get(i) will fetch the value from the dictionary. If the key does not exist, it returns zero.
classSolution:
classSparseArray:
def __init__(self):
self.map: Dict[int, int] = {}
self.size: int =0definit(self, arr: List[int], size: int) ->None:
self.size = size
for i, val in enumerate(arr):
if val !=0:
self.map[i] = val
defset(self, i: int, val: int) ->None:
if i >= self.size:
raiseIndexError("Index out of bounds")
if val ==0:
self.map.pop(i, None)
else:
self.map[i] = val
defget(self, i: int) -> int:
if i >= self.size:
raiseIndexError("Index out of bounds")
return self.map.get(i, 0)