Skip to content

Instantly share code, notes, and snippets.

@aceakash
Last active August 29, 2015 14:15
Show Gist options
  • Save aceakash/3169b0540439ad3b1207 to your computer and use it in GitHub Desktop.
Save aceakash/3169b0540439ad3b1207 to your computer and use it in GitHub Desktop.
Sum of intervals problem

Write a function called sumIntervals that accepts an array of intervals, and returns the sum of all the interval lengths.

Overlapping intervals should only be counted once.

Intervals

Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4.

Overlapping Intervals

List containing overlapping intervals:

[
   [1,4],
   [7, 10],
   [3, 5]
]

The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4.

Examples

sumIntervals( [
   [1,2],
   [6, 10],
   [11, 15]
] ); //=> returns 9

sumIntervals( [
   [1,4],
   [7, 10],
   [3, 5]
] ); //=> returns 7

sumIntervals( [
   [1,5],
   [10, 20],
   [1, 6],
   [16, 19],
   [5, 11]
] ); //=> returns 19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment