15
0
Given a list of intervals, perform the union of them, and reduce overlaps.
That means, overlapping parts are reduced. ([a, b] U [c, d] = [a, d]
if b > c
)
Assuming all a < b in all intervals [a, b]
.
Implement as a function of a list of input intervals -> list of output intervals.
Shortest code wins. You cannot use any existing libraries.
Clarifications:
- Open and closed intervals are not distinguished.
- Intervals for real numbers, not integers. (
[2, 3], [4, 5] -> [2, 3], [4, 5]
) - No need to sort output intervals
- The order if inputs do not matter
- Illegal inputs are only
[a, b]
whereb >= a
, it has nothing to do with the order of input intervals and the number of input intervals. - You do not need to show an error message on undefined behaviors
Examples (with number lines)
[2, 4], [7, 9] --> [2, 4], [7, 9]
234
789
-> 234 789
[1, 5], [2, 10] --> [1, 10] (overlapping [2, 5] reduced)
12345
234567890
-> 1234567890
[2, 4], [3, 6], [8, 9] -> [2, 6], [8, 9]
234
3456
89
-> 23456 89
[4, 2], [2, 2] -> (undefined behavior: against the assumption)
4Will the intervals always be sorted as they are in your examples? – Peter Olson – 2011-04-21T06:18:32.247
bounds on the numbers? – st0le – 2011-04-21T09:44:39.087
1Why don't [2, 3], [4, 5] overlap, or [2, 4], [4, 5] either? They both yield 2345. – mellamokb – 2011-04-21T14:04:40.470
2Are the intervals only on the set of integers? – Lowjacker – 2011-04-21T15:31:27.713
2We need some clarification: 1) Is [4,5],[1,2] legal input? 2) Should the output of [2,3],[4,5] be [2,5] or [2,3],[4,5]? 3) Should the output of [2,3],[3,4] be [2,4] or [2,3],[3,4]? – MtnViewMark – 2011-04-22T02:42:09.803
1Thanks for clarifications, but "No need to sort" means what? That the output needn't be sorted? Or that the input is already sorted? – MtnViewMark – 2011-04-23T01:33:08.397
1Wondering why you picked the Python entry? It wasn't the shortest.. what made it be the winner? – MtnViewMark – 2011-04-24T05:58:01.940