Try to solve the Dot Product of Two Sparse Vectors problem.
Statement
We must calculate the dot product of two given sparse vectors, nums1
and nums2
.
Create a SparseVector class:
Constructor(): Initializes the object with the vector.
DotProduct(): Computes the dot product between the current instance of the vector and the other.
Note: A sparse vector is a vector that contains mostly zero values. Therefore, we should store the sparse vectors and calculate the dot product accordingly.
Constraints:
nums1.length
nums2.length
nums1[i]
,nums2[i]
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Dot Product of Two Sparse Vectors
What is the result of the dot product of the sparse vectors nums1
and nums2
?
0
12
21
15
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding on how to solve this problem.
Try it yourself
Implement your solution in the following coding playground.
class SparseVector:def __init__(self, nums):# Write your code herepassdef dot_product(self, vec):# Write your code herereturn -1