Advertisement
hoangreal

Sparse Vector Dot Product

Oct 19th, 2024 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | Source Code | 0 0
  1. class SparseVector:
  2.     """
  3.    Represents a sparse vector and performs dot product.
  4.  
  5.    Time Complexity:
  6.    ----------------
  7.    O(min(n1, n2))
  8.    - n1, n2: number of non-zero elements in both vectors.
  9.    
  10.    Space Complexity:
  11.    -----------------
  12.    O(n1 + n2)
  13.    - n1, n2: space for storing non-zero elements of both vectors.
  14.    """
  15.  
  16.     def __init__(self, nums: List[int]):
  17.         # Store the non-zero values and their indices
  18.         self.dense_index_num_pairs = [(i, num) for i, num in enumerate(nums) if num > 0]
  19.         self.size = len(self.dense_index_num_pairs)
  20.    
  21.     """
  22.     The O(n) time complexity occurs during the initialization of the SparseVector object, not during each      
  23.     computation. This means we pay the cost once, and if you perform many dot product operations with the same  
  24.     vector, the initial O(n) cost is amortized over all these operations, making each operation more efficient.
  25.     """
  26.     def solve(self, vec: "SparseVector") -> int:
  27.         answer = 0
  28.         min_size = min(self.size, vec.size)
  29.        
  30.         # Determine which vector is smaller
  31.         running_vector = self.dense_index_num_pairs if min_size == self.size else vec.dense_index_num_pairs
  32.         other_vector_map = dict(vec.dense_index_num_pairs) \
  33.             if min_size == self.size else dict(self.dense_index_num_pairs)
  34.  
  35.         # Compute dot product by multiplying matching indices
  36.         for my_index, my_num in running_vector:
  37.             if my_index in other_vector_map:
  38.                 answer += my_num * other_vector_map[my_index]
  39.        
  40.         return answer
  41.  
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement