This is a design question.
Write the implementation for the following functions:
void addInterval(int from, int to)
int getTotalCoveredLength()addInterval() adds intervals to an internal structure and getTotalCoveredLength() gets the the total covered length of the intervals, if several intervals intersect, the intersect should only be counted once e.g.
addInterval(3, 6)
addInterval(8, 9)
addInterval(1, 5)
getTotalCoveredLength() -> 6
i.e. [1,5] and [3,6] intersect and give a total covered interval [1,6]
[1,6] and [8,9] don't intersect so total covered length is a sum for both intervals, that is 5 + 1 = 6.
For addInterval, I was thinking of doing binary insert into a sorted vector of intervals (sorted by from), then before inserting check if overlap with the left or right elements, if we do, merge them, then check the left and right again.
How would you approach this problem?
Thanks!