Please use Laptop/Desktop or any other large screen for the Mock Interview Session.

Dot Product of Two Sparse Vectors



YouTube Video Thumbnail
Link

Watch above sample mock interview video to see how it works.
Login and Buy Premium to Start the Interview



Dot Product of Sparse Arrays

Dot Product of Sparse Arrays

Problem Statement

You are given two sparse arrays. Your task is to calculate their dot product efficiently.

Design a class named SparseArray with the following features:

  • SparseArray(arr): Initializes the object with the array arr
  • computeDot(otherArray): Returns the dot product of the current SparseArray instance with another SparseArray instance otherArray

Note: A sparse array contains mostly zero values. You should store the sparse array in a way that uses memory efficiently and allows fast dot product computation.

Examples

Array1 = [2,0,0,1,4], Array2 = [0,5,0,3,0]
Result: 3
Explanation:
sa1 = SparseArray(Array1), sa2 = SparseArray(Array2)
sa1.computeDot(sa2) = 2*0 + 0*5 + 0*0 + 1*3 + 4*0 = 3
    
Array1 = [0,3,0,0,0], Array2 = [0,0,0,0,6]
Result: 0
Explanation:
sa1 = SparseArray(Array1), sa2 = SparseArray(Array2)
sa1.computeDot(sa2) = 0*0 + 3*0 + 0*0 + 0*0 + 0*6 = 0
    
Array1 = [0,2,0,0,1,0,0], Array2 = [4,0,0,0,5,0,7]
Result: 7
Explanation:
sa1 = SparseArray(Array1), sa2 = SparseArray(Array2)
sa1.computeDot(sa2) = 0*4 + 2*0 + 0*0 + 0*0 + 1*5 + 0*0 + 0*7 = 7
    

Constraints

  • Length of arrays is between 1 and 90,000 inclusive
  • Each element in arrays is between 0 and 120 inclusive