LeetCode #1570 Dot Product of Two Sparse Vectors

LeetCode #1570 Dot Product of Two Sparse Vectors

Difficulty: Medium

Table of contents

No heading

No headings in the article.

The question is pretty simple once you understand the hint:

You should store the sparse vector efficiently.

We can use the dictionary data structure to solve this.

Link: LeetCode #1570 Dot Product of Two Sparse Vectors

/**
 * @param {number[]} nums
 * @return {SparseVector}
 */
var SparseVector = function(nums) {
    // Initialize map
    this.map = new Map();

    // Iterate through the array
    // Store the index and non-zero values
    for(let i =0; i<nums.length;i++){
        if(nums[i] >0){
            this.map.set(i, nums[i]);
        }
    }
};

// Return the dotProduct of two sparse vectors
/**
 * @param {SparseVector} vec
 * @return {number}
 */
SparseVector.prototype.dotProduct = function(vec) {
    let sum = 0;

    // Iterate through the map
    // Check if the index matches, multiply the values
    // Add the result to sum
    for (const [i, v] of this.map) {
        if(vec.map.has(i)){
            sum += vec.map.get(i)*this.map.get(i)
        }
    }

    return sum;
};