In Python, what are the running time and space complexities if a list is converted to a set?
Example:
data = [1,2,3,4,5,5,5,5,6]
# this turns list to set and overwrites the list
data = set(data)
print data
# output will be (1,2,3,4,5,6)
Converting a list to a set requires that every item in the list be visited once, O(n). Inserting an element into a set is O(1), so the overall time complexity would be O(n).
Space required for the new set is less than or equal to the length of the list, so that is also O(n).
Here's a good reference for Python data structures.
As others have stated regarding the runtime, the set creation time is O(N) for the entire list, and set existence check is O(1) for each item.
But their comments on memory usage being the same between lists and sets are incorrect.
In python, sets can use 3x to 10x more memory than lists. Set memory usage growth still O(N), but it's always at least 3x more than lists. Maybe because of needing to keep in memory all those hashes.