Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of intervals

I've got a class representing an interval. This class has two properties "start" and "end" of a comparable type. Now I'm searching for an efficient algorithm to take the union of a set of such intervals.

Thanks in advance.

like image 253
drvj Avatar asked Jun 23 '09 19:06

drvj


People also ask

Is union of intervals an interval?

Unions: Any union of intervals with a common point is an interval.

How do you find the union between sets?

The union of two sets is a set containing all elements that are in A or in B (possibly both). For example, {1,2}∪{2,3}={1,2,3}. Thus, we can write x∈(A∪B) if and only if (x∈A) or (x∈B). Note that A∪B=B∪A.


1 Answers

Sort them by one of the terms (start, for example), then check for overlaps with its (right-hand) neighbor as you move through the list.

class tp:
    def __repr__(self):
        return "(%d,%d)" % (self.start, self.end)

    def __init__(self, start, end):
        self.start = start
        self.end = end


s = [tp(5, 10), tp(7, 8), tp(0, 5)]
s.sort(key=lambda self: self.start)
y = [s[0]]
for x in s[1:]:
    if y[-1].end < x.start:
        y.append(x)
    elif y[-1].end == x.start:
        y[-1].end = x.end
like image 59
geocar Avatar answered Oct 13 '22 07:10

geocar