LeetCode 1570: Dot Product of Two Sparse Vectors Solution

Master LeetCode problem 1570 (Dot Product of Two Sparse Vectors), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1570. Dot Product of Two Sparse Vectors

Problem Explanation

Explanation

To compute the dot product of two sparse vectors efficiently, we can store only the non-zero elements of the vectors along with their indices. Then, we can iterate over these non-zero elements and multiply the corresponding elements from both vectors. Finally, we sum up these products to get the dot product.

The time complexity of this approach is O(n) where n is the number of non-zero elements in the vectors, as we only iterate over the non-zero elements. The space complexity is also O(n) to store the non-zero elements and their indices.

Solution Code

class SparseVector {
    Map<Integer, Integer> map;

    SparseVector(int[] nums) {
        map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                map.put(i, nums[i]);
            }
        }
    }

    public int dotProduct(SparseVector vec) {
        int product = 0;
        for (int i : map.keySet()) {
            if (vec.map.containsKey(i)) {
                product += map.get(i) * vec.map.get(i);
            }
        }
        return product;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1570 (Dot Product of Two Sparse Vectors)?

This page provides optimized solutions for LeetCode problem 1570 (Dot Product of Two Sparse Vectors) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1570 (Dot Product of Two Sparse Vectors)?

The time complexity for LeetCode 1570 (Dot Product of Two Sparse Vectors) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1570 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1570 in Java, C++, or Python.

Back to LeetCode Solutions