Prepin
Log in

Calculate the dot product of two sparse vectors.

Approach / Explanation

The interviewer is requesting your help in calculating the dot product of two sparse vectors. To put it simply, your job is to create an algorithm that computes the dot product of these two sparse vectors. The formula for the dot product of two vectors is a[1]*b[1] + a[2]*b[2] + .... + a[n]*b[n] , where vectors a and b each have a length of n. Sparse vectors are characterized by having most of their elements equal to zero, which presents a great opportunity to optimize the computation by concentrating on the non-zero elements only. Here are some important aspects to keep in mind while responding: Grasping the definition of 'sparse vectors'. Being able to implement an efficient algorithm or method for calculating the dot product of sparse vectors. Paying attention to both performance and memory consumption.

Suggested Answer

A method to calculate the dot product of two sparse vectors involves iterating through the non-zero elements of the vectors and summing their products. Below is a potential implementation in Python: def dotProduct ( vec1 , vec2 ) : if len ( vec1 ) > len ( vec2 ) : vec1 , vec2 = vec2 , vec1 result = 0 for key in vec1 : if key in vec2 : result += vec1 [ key ] * vec2 [ key ] return result In this approach, 'vec1' and 'vec2' are represented as dictionaries, where the keys denote the indices of the non-zero elements, and the values correspond to the non-zero entries themselves. This method leverages the sparsity of the vectors by performing calculations only when both vectors have a non-zero entry, which significantly decreases computation time.

Alternative Answer

One way to enhance the computational efficiency of the dot product operation is by using a data structure that is more suitable for sparse data, such as a Hash Map. Below is a potential implementation in Java: public int dotProduct ( Map < Integer , Integer > vec1 , Map < Integer , Integer > vec2 ) { if ( vec1 . size ( ) > vec2 . size ( ) ) { return dotProduct ( vec2 , vec1 ) ; } int result = 0 ; for ( Map . Entry < Integer , Integer > entry : vec1 . entrySet ( ) ) { if ( vec2 . containsKey ( entry . getKey ( ) ) ) { result += entry . getValue ( ) * vec2 . get ( entry . getKey ( ) ) ; } } return result ; } In this approach, vec1 and vec2 are hash maps where the keys represent the indices of non-zero entries, and the values correspond to those non-zero entries. This method effectively bypasses unnecessary calculations by ignoring zero entries in both vectors, thus reducing computational complexity and conserving memory space.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Meta (Facebook)

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.