Dot Product of Two Sparse Vectors - Problem

Given two sparse vectors, compute their dot product.

Implement class SparseVector:

  • SparseVector(nums) Initializes the object with the vector nums
  • dotProduct(vec) Compute the dot product between the instance of SparseVector and vec

A sparse vector is a vector that has mostly zero values. You should store the sparse vector efficiently and compute the dot product between two SparseVector.

Follow up: What if only one of the vectors is sparse?

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
Output: 8
💡 Note: Dot product = 1×0 + 0×3 + 0×0 + 2×4 + 3×0 = 0 + 0 + 0 + 8 + 0 = 8
Example 2 — All Zeros
$ Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
Output: 0
💡 Note: No overlapping non-zero elements: 0×0 + 1×0 + 0×0 + 0×0 + 0×2 = 0
Example 3 — Same Position Non-Zero
$ Input: nums1 = [0,1,0,0,2,0], nums2 = [1,0,0,0,3,0]
Output: 6
💡 Note: Only position 4 has non-zero in both: 0×1 + 1×0 + 0×0 + 0×0 + 2×3 + 0×0 = 6

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 105
  • 0 ≤ nums1[i], nums2[i] ≤ 100

Visualization

Tap to expand
Sparse Vector Dot Product OptimizationInput: Two sparse vectors1002303040Extract Non-Zero ElementsVector 10: 1, 3: 2, 4: 3Vector 21: 3, 3: 4Find Common Index 3: 2 × 4 = 8Result: 8
Understanding the Visualization
1
Input Sparse Vectors
Two vectors with mostly zero values
2
Store Non-Zero Only
Extract and store only non-zero elements with indices
3
Compute Dot Product
Find overlapping indices and multiply corresponding values
Key Takeaway
🎯 Key Insight: Store only non-zero elements to skip unnecessary multiplications by zero and save memory
Asked in
Facebook 15 Amazon 8 Google 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen