I've noticed the table of the time complexity of set operations on the python official website. But i just wanna ask what's the time complexity of converting a list to a set, for instance,
l = [1, 2, 3, 4, 5] s = set(l)
I kind of know that this is actually a hash table, but how exactly does it work? Is it O(n) then?
The time complexity of converting a list to a set is linear in the number of list elements. So, if the set has n elements, the asymptotic complexity is O(n). The reason is that you need to iterate over each element in the list which is O(n), and add this element to the set which is O(1).
The average time complexity of the in operator for lists is O(n) . It becomes slower when there are many elements. The execution time varies greatly depending on the position of the value to look for. It takes the longest time when its value is at the end or does not exist.
You can use python set() function to convert list to set.It is simplest way to convert list to set. As Set does not allow duplicates, when you convert list to set, all duplicates will be removed in the set. Let's understand with the help of example.
Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal). The time complexity of set operations is O(log n) while for unordered_set, it is O(1).
Yes. Iterating over a list is O(n)
and adding each element to the hash set is O(1)
, so the total operation is O(n)
.
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