Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-055

Sparse Vector Dot Product

Problem

Compute the dot product of two sparse vectors represented as dictionaries.

Each dictionary maps an index (as a string key) to its value, and missing indices are zero. Iterate over the first dictionary and add its value times the matching value from the second when the key is present.

Return the integer dot product (0 when there are no shared indices).

Hint

Only keys present in both dictionaries contribute to the product.

Test cases

case 1
in: [{"0":1,"3":5},{"0":2,"3":-1,"7":4}]
expected: -3
case 2
in: [{"1":2},{"2":3}]
expected: 0
case 3
in: [{},{}]
expected: 0
case 4
in: [{"5":-3},{"5":4}]
expected: -12
Starter codePython
def sparse_dot(a, b):
    # Your code here
    pass

4 test cases · run your code against them in the editor