The question explains it, but what is the time complexity of the set difference operation in Python?
EX:
A = set([...])
B = set([...])
print(A.difference(B)) # What is the time complexity of the difference function?
My intuition tells me O(n)
because we can iterate through set A and for each element, see if it's contained in set B in constant time (with a hash function).
Am I right?
(Here is the answer that I came across: https://wiki.python.org/moin/TimeComplexity)
looks that you're right, difference is performed with
O(n)
complexity in the best casesBut keep in mind that in worst cases (maximizing collisions with hashes) it can raise to
O(n**2)
(since lookup worst case isO(n)
: How is set() implemented?, but it seems that you can generally rely onO(1)
)As an aside, speed depends on the type of object in the
set
. Integers hash well (roughly as themselves, with probably some modulo), whereas strings need more CPU.https://wiki.python.org/moin/TimeComplexity suggests that its O(cardinality of set A) in the example you described.
My understanding that its
O(len(A))
and notO(len(B))
because, you only need to check if each element in setA is present in setB. Each lookup in setB isO(1)
, hence you will be doinglen(A) * O(1)
lookups on setB. Since O(1) is constant, then itsO(len(A))
Eg:
When
A-B
is called, iterate through every element in A (only 5 elements), and check for membership in B. If not found in B, then it will be present in the result.Note: Of course all this is amortised complexity. In practice, each lookup in setB could be more than
O(1)
.