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
Dot Product of Two Sparse Vectors INPUT nums1 = [1,0,0,2,3] 1 0 0 2 3 0 1 2 3 4 nums2 = [0,3,0,4,0] 0 3 0 4 0 0 1 2 3 4 Hash Map Storage: map1 {0: 1} {3: 2} {4: 3} map2 {1: 3} {3: 4} Gray = zero values (skipped) ALGORITHM STEPS 1 Build Hash Maps Store only non-zero elements index --> value 2 Iterate Smaller Map Loop through map1 keys 3 Check Common Indices If index exists in map2 4 Multiply and Sum result += v1 * v2 Computation: idx 0: 1 * 0 = 0 (skip) idx 3: 2 * 4 = 8 (OK) idx 4: 3 * 0 = 0 (skip) Sum = 8 FINAL RESULT Dot Product Formula: sum(a[i] * b[i]) for all i Only index 3 contributes: 2 nums1[3] x 4 nums2[3] = Output: 8 OK - Dot product computed! Time: O(min(n,m)) | Space: O(n+m) Key Insight: Using hash maps to store only non-zero elements reduces space from O(n) to O(k) where k is the number of non-zeros. For dot product, we only need to check indices that exist in BOTH vectors - zeros contribute nothing! Follow-up: If only one vector is sparse, iterate over the sparse one and use array access for the dense vector. TutorialsPoint - Dot Product of Two Sparse Vectors | Hash Map Approach
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