Estimated linear time O (total number of elements):
def all_disjoint(sets): union = set() for s in sets: for x in s: if x in union: return False union.add(x) return True
This is optimal under the assumption that your input is a collection of sets represented as some sort of disordered data structure (hash table?), Because you need to look at each element at least once.
You can do much better by using a different view for your sets. For example, keeping a global hash table that stores for each element the number of sets in which it is stored, you can perform all the specified operations optimally, as well as check disjointness in O (1).
Niklas B. Mar 16 '14 at 5:08 2014-03-16 05:08
source share