self.array = nums: what is time complexity for assignment of lists in python?

Question:

I was solving Dot Product of Two Sparse Vectors (Given two sparse vectors, compute their dot product.) and I got confused about time complexity.

For solution:

class SparseVector:
    def __init__(self, nums):
        self.array = nums

    def dotProduct(self, vec):
        result = 0
        for num1, num2 in zip(self.array, vec.array):
            result += num1 * num2
        return result

it says in answer that

Time complexity: O(n) for both constructing the sparse vector and calculating the dot product.

Why time complexity of __init__ is O(n)? I thought that self.array = nums is simple assignment like list_1 = list_2 and should has time complexity O(1).

Asked By: illuminato

||

Answers:

You’re right, the assignment is O(1). Assignment in Python never does any copying unless you explicitly make a copy, you just end up with two references to the same object. Doesn’t matter how large the object is.

Answered By: Mark Ransom

To be precise, time complexity is O(n*m). Where n and m are the sizes of the arrays.

Answered By: Farzan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.