Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is time complexity of a list to set conversion?

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?

like image 730
lxuechen Avatar asked Jan 06 '16 20:01

lxuechen


People also ask

What is the time complexity of converting list in set?

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).

What is the time complexity of list () in Python?

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.

Can you convert a list to a set?

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.

What is the time complexity of set?

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).


1 Answers

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).

like image 87
Mad Physicist Avatar answered Sep 28 '22 00:09

Mad Physicist