Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SparseVector:
- """
- Represents a sparse vector and performs dot product.
- Time Complexity:
- ----------------
- O(min(n1, n2))
- - n1, n2: number of non-zero elements in both vectors.
- Space Complexity:
- -----------------
- O(n1 + n2)
- - n1, n2: space for storing non-zero elements of both vectors.
- """
- def __init__(self, nums: List[int]):
- # Store the non-zero values and their indices
- self.dense_index_num_pairs = [(i, num) for i, num in enumerate(nums) if num > 0]
- self.size = len(self.dense_index_num_pairs)
- """
- The O(n) time complexity occurs during the initialization of the SparseVector object, not during each
- computation. This means we pay the cost once, and if you perform many dot product operations with the same
- vector, the initial O(n) cost is amortized over all these operations, making each operation more efficient.
- """
- def solve(self, vec: "SparseVector") -> int:
- answer = 0
- min_size = min(self.size, vec.size)
- # Determine which vector is smaller
- running_vector = self.dense_index_num_pairs if min_size == self.size else vec.dense_index_num_pairs
- other_vector_map = dict(vec.dense_index_num_pairs) \
- if min_size == self.size else dict(self.dense_index_num_pairs)
- # Compute dot product by multiplying matching indices
- for my_index, my_num in running_vector:
- if my_index in other_vector_map:
- answer += my_num * other_vector_map[my_index]
- return answer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement