First answer: if you are dealing with sets of numbers, you can implement the set as a sorted vector of individual elements. Then you can implement the union (S1, S2) simply as a merge operation (check for duplicates), which takes time O (n), where n = the sum of powers.
Now my first answer is a bit naive. And Akusete is right: you can, and you must, implement the set as a hash table (the set must be a common container, and not all objects can be sorted!). Then both the search and the insert are O (1), and, you guessed it, the union takes O (n) time.
(Looking at your Python code) Python collections are implemented using hash tables. Read this interesting thread . See Also this implementation , which uses sorted vectors instead.
source share