Sparse Array Implementation

easy
array dsa algorithm
🏢facebook
0 views0 likes

Problem Description

Design a SparseArray class that efficiently stores and manipulates a large array predominantly filled with zeros. This class should support initializing with a large array, updating values at specific indices, and fetching values from specific indices, all while optimizing for space.

Constraints:

  • The large array can contain any integer values, with most of them being zero.
  • Indices are zero-based.
  • The size parameter indicates the total length of the array.
  • Operations set and get should operate in efficient time complexity.

Methods:

  1. init(arr, size): Initializes the sparse array with the given large array and size. Only non-zero elements are stored efficiently.
  2. set(i, val): Updates the value at index i with val. If val is 0 and the index is currently stored, it should be removed from the storage.
  3. get(i): Returns the value at index i. If i is not stored, return 0.
# Initialize with a large array and its size
sparseArray = SparseArray([1, 0, 0, 0, 2, 0, 0, 3], 8)

# Set value at index 5 to 5
sparseArray.set(5, 5)

# Get value at index 5, should return 5
print(sparseArray.get(5))  # Output: 5

# Get value at index 1, should return 0 since it's not set
print(sparseArray.get(1))  # Output: 0

Hints

[object Object]

[object Object]

[object Object]