You need to implement a data structure for a sparse vector of integers and support efficient computation of the dot product between two such vectors.
-
The length
n
of the vector can be large (e.g., up to 10^5), but only a small number of positions contain non-zero values.
-
You are initially given each vector as a dense integer array
nums
of length
n
.
Design a SparseVector class with:
-
A constructor
SparseVector(int[] nums)
that stores the vector in a space-efficient way.
-
A method
int dotProduct(SparseVector other)
that returns the dot product of the current vector with another sparse vector.
The dot product of two vectors a and b of length n is defined as:
a · b = a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1].
Specify your data representation, and analyze the time and space complexity of:
-
Constructing the sparse vector.
-
Computing the dot product.
You do not need to provide actual code, but your algorithm must be clearly described.