Advertisement
smj007

LC 1570: Dot product of two sparse vectors

Apr 18th, 2025
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.00 KB | None | 0 0
  1. """
  2. Trade offs of using pairs vs hashmap: using simple list of pairs avoids
  3. the complexity and overhead that comes with hashing. Dicts have internal overhead since hash tables need to store keys and handle collisions. ordered
  4. pairs use less memory than hashmap for very sparse vector
  5.  
  6. Time complexity: let L1 and L2 be the number of non-zero elements in each
  7. of the paits. Then the TC is O(L1 + L2). Notice with hashmap based approach
  8. So time is also O(min(n, m)) on average, but can degrade with hash collisions.
  9.  
  10. Space complexity: O(L) for creating the index value pairs (not O(l1+l2))
  11. """
  12.  
  13. class SparseVector:
  14.     def __init__(self, nums: List[int]):
  15.         self.pairs = []
  16.         for i in range(len(nums)):
  17.             if nums[i]!=0:
  18.                 self.pairs.append([i, nums[i]])
  19.  
  20.     # Return the dotProduct of two sparse vectors
  21.     def dotProduct(self, vec: 'SparseVector') -> int:
  22.         i, j = 0, 0
  23.         product = 0
  24.         pairs_b = self.pairs
  25.         pairs_a = vec.pairs
  26.         if len(pairs_a) > len(pairs_b):
  27.             return vec.dotProduct(self)
  28.  
  29.         while i < len(pairs_a) and j < len(pairs_b):
  30.             if pairs_a[i][0] < pairs_b[j][0]:
  31.                 i += 1
  32.             elif pairs_a[i][0] > pairs_b[j][0]:
  33.                 j += 1
  34.             else:
  35.                 product += pairs_a[i][1]*pairs_b[j][1]
  36.                 i += 1
  37.                 j += 1
  38.  
  39.         return product
  40.  
  41. """
  42. In case of binary search, if we have a vector which is largely very
  43. sparse and the other one not so much it would make sense to run
  44. binary search
  45.  
  46. Time complexity: let n and me be the number of non-zero elements in the
  47. small and large vectors. such that n<<m, in that case we would like
  48. to iterate over the the n and search over the bigger m. < nlog(m) >
  49. Space complexity: O(n)
  50. """
  51.  
  52. class SparseVector:
  53.     def __init__(self, nums: List[int]):        
  54.         self.pairs = []
  55.         for i in range(len(nums)):
  56.             if nums[i]!=0:
  57.                 self.pairs.append([i, nums[i]])
  58.  
  59.     @staticmethod
  60.     def find_target(index, pairs):
  61.        
  62.         left = 0
  63.         right = len(pairs)-1
  64.  
  65.         while (left<=right):
  66.             mid = (left+right)//2
  67.             if pairs[mid][0] == index:
  68.                 return mid
  69.             elif pairs[mid][0] < index:
  70.                 left = mid + 1
  71.             else:
  72.                 right = mid - 1
  73.         return -1
  74.            
  75.     # Return the dotProduct of two sparse vectors
  76.     def dotProduct(self, vec: 'SparseVector') -> int:
  77.        
  78.         # iterate over the vector number pairs instead
  79.         if len(vec.pairs) < len(self.pairs):
  80.             return vec.dotProduct(self)
  81.  
  82.         n = len(self.pairs)
  83.         m = len(vec.pairs)
  84.         product = 0
  85.  
  86.         for index, value in self.pairs:
  87.             # find target value
  88.             target_index = SparseVector.find_target(index, vec.pairs)
  89.             if target_index != -1:
  90.                 product += value*vec.pairs[target_index][1]
  91.  
  92.         return product
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement