Wondering the time complexity of remove of list, and remove of set.
My thought and study result is,
O(n)
O(1)
.I just studied some discussion, but never prove it. If anyone could shed some lights, it will be great. Especially how set implements with O(1)
removal?
Using Python 2.7.
a = set([1,2,3,4,5])
b = [1,2,3,4,5]
a.remove(3)
b.remove(3)
print a
print b
Removal of list is O(n) Removal of set is O(1) .
HashSet 's remove() takes O(1) expected time to locate the element to be removed - the hashCode() takes you to the bin that contains the element, and each bin is expected to have a small number of entries, so finding the element in the bin and removing it should take constant time.
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).
You can easily omit declaration of perfect squares, count and total_length, as they aren't needed, as explained further. This will reduce both Time and Space complexities of your code. Also, you can use Fast IO, in order to speed up INPUTS and OUTPUTS This is done by using 'stdin. readline', and 'stdout.
From the docs:
list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.
Without going into the details of the implementation, the item to remove can be anywhere in the list. A linear scan time is necessary in order to find the item before it can be removed. Once you find the index of the item to remove, you need to shift all the elements down by one index. In any case there's index
amount of traversal and size - index
amount of shifting involved. Therefore the removal time is equivalent to traversing the entire list: O(n).
You can find the source here: https://hg.python.org/cpython/file/tip/Objects/listobject.c#l2197 (also look for list_ass_slice(..)
).
However, a set is different. It uses the hash value of the object being stored to locate it in its buckets. On an average, locating of objects using hash value is almost constant time. Note that it might not always be constant time where there's hash collision and a further search is required. But assuming a good hash function, it usually is.
UPDATE: I must thank Stefan Pochmann for pointing out the mistake.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With