Time complexity of python set operations?

后端 未结 3 1044
感动是毒
感动是毒 2020-11-27 14:37

What is the the time complexity of each of python\'s set operations in Big O notation?

I am using Python\'s set type for an operation on a large number of items. I w

相关标签:
3条回答
  • 2020-11-27 14:56

    The other answers does not talk about 2 crucial operations on sets: Unions and intersections. In the worst case, union will take O(n+m) whereas intersection will take O(min(x,y)) provided that there are not many element in the sets with the same hash. A list of time complexities of common operations can be found here: https://wiki.python.org/moin/TimeComplexity

    0 讨论(0)
  • 2020-11-27 14:58

    The operation in should be independent from he size of the container, ie. O(1) -- given an optimal hash function. This should be nearly true for Python strings. Hashing strings is always critical, Python should be clever there and thus you can expect near-optimal results.

    0 讨论(0)
  • 2020-11-27 15:10

    According to Python wiki: Time complexity, set is implemented as a hash table. So you can expect to lookup/insert/delete in O(1) average. Unless your hash table's load factor is too high, then you face collisions and O(n).

    P.S. for some reason they claim O(n) for delete operation which looks like a mistype.

    P.P.S. This is true for CPython, pypy is a different story.

    0 讨论(0)
提交回复
热议问题