Given two sets A and B, what is the common algorithm used to find their union, and what is it’s running time?
My intuition:
a = set((1, 2, 3)) b = set((2, 3, 5)) union = set() for el in a: union.add(el) for el in b: union.add(el)
Add checks for a collision, which is O(1), and then adds the element, which is (??). This is done n times (where n is |a| + |b|). So this is O(n * x) where x is avg running time for the add operation.
Is this correct?
This is very much implementation dependent. Others have mentioned sets based on comparables (have a less-than for sorting) or hashables (have a good hash function for hashing). Another possible implementation involved ‘union-find’, which only supports a specialized subset of usual set operations but is very fast (union is amortized constant time, I think?), you can read about it here
http://en.wikipedia.org/wiki/Union_find
and see an example application here
http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!220.entry