Design Gurus Logo
Dot Product of Two Sparse Vectors (medium)

Problem Statement

Given two sparse vectors, efficiently compute the dot product of them.

A sparse vector is one in which most elements are zero.

Implement class Solution:

  • Solution(nums) Initializes the object with the vector nums
  • dotProduct(vec) Calculates the dot product between the vec and instance of Solution.

Examples

  • Example 1:

    • Input: vec1 = [1, 0, 0, 2], vec2 = [2, 3, 0, 1]
    • Expected Output: 4
    • Justification: The dot product is (1*2) + (0*3) + (0*0) + (2*1) = 2 + 0 + 0 + 2 = 4.
  • Example 2:

    • Input: vec1 = [0, 0, 0, 0], vec2 = [1, 1, 1, 1]
    • Expected Output: 0
    • Justification: Since vec1 is all zeros, the dot product is 0 regardless of vec2's values.
  • Example 3:

    • Input: vec1 = [1, 0, 0, 2, 3], vec2 = [0, 3, 0, 4, 0]
    • Expected Output: 8
    • Justification: The dot product is (1*0) + (0*3) + (0*0) + (2*4) + (3*0) = 8.

Constraints:

  • n == nums1.length == nums2.length
  • 1 <= n <= 10<sup>5</sup>
  • 0 <= nums1[i], nums2[i] <= 100

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory