# Identifying and isolating sections of overlap in a set of integer intervals

I have a very large array like the following:

{{1,10},{8,9},{9,20},{34,40},{41,42},{43,50},{47,53},...};


Now, imagine that every element in the array corresponds to an integer interval. I'd like to delete elements in the array that fall within a larger interval, and whenever there is an interval-interval overlap, I'd like to shrink the intersecting intervals to eliminate the overlap and then add the former section where the overlap occurred as a new element to a separate array (here I'm calling this overlapArray).

Perhaps this is best explained by example. Looking at the smaller case:

{{1,10},{8,9},{9,20},{34,40}...}


We notice that there is an overlap between the first three elements of the array, and that the element {8,9} falls entirely in this overlap section. So we this array becomes the following after our procedure:

{{1,7},{11,20},{34,40}...}

overlapArray = {{8,10}};


Now for the full example, this:

{{1,10},{8,9},{9,20},{34,40},{41,42},{43,50},{47,53},...};


Becomes:

{{1,7},{11,20},{34,40},{41,42},{43,46},{51,53}

overlapArray = {{8,10},{47,50}};


Is there an elegant way to do this with list operations in Mathematica v9?

• @Kuba Sorry, were you preparing a response? I thought it was too open-ended and that it was a bad question. I thought from this, and your previous answer, I could figure out how to do it. But if you have a response, or you think it was wrong for me to do this, I will undelete it! Apr 1, 2014 at 9:49
• @Kuba Whatever you'd like, my priority was just not to be a nuisance here, so I was acting accordingly. Apr 1, 2014 at 9:51
• @Kuba It's back! Apr 1, 2014 at 10:00

I like this one :P

list = {{1, 10}, {8, 9}, {9, 20}, {34, 40}, {41, 42}, {43, 50}, {47, 53}}

Composition[
Split[#, #2 - #1 == 1 &][[ All , {1, -1}]] &,
Sort,
DeleteCases[#, {_, 1}][[ All , 1]] &,
Tally,
Flatten,
Range @@@ # &
][list]

 {{8, 10}, {47, 50}}

• This can be written in compact way but now it is more readable.
– Kuba
Apr 1, 2014 at 9:52
• Cool! That sure was fast. Is there a way to modify the original list to get: {{1,7},{11,20},{34,40},{41,42},{43,46},{51,53}? BTW, I can't upvote yet due to my low rep. Apr 1, 2014 at 9:52
• @Bob2Alice just change DeleteCases to Cases :)
– Kuba
Apr 1, 2014 at 9:53
• Ooooh nice nice. +1 Apr 1, 2014 at 9:56
• Slickly done. +1
– ciao
Apr 1, 2014 at 9:57