Total Covered Length of Intervals
Ola, as a leading ride-sharing platform, constantly optimizes driver schedules and trip assignments. A fundamental task involves understanding time segments, such as when a driver is available or when a vehicle is in use. This problem focuses on calculating the total effective duration covered by various time windows, especially when these windows might overlap. This is crucial for accurate resource allocation and operational planning.
Your task is to implement a function that takes a list of time intervals and calculates the total length of time effectively covered by these intervals. If multiple intervals overlap, the overlapping portions should only be counted once towards the total length. Think of it as finding the length of the union of all given intervals.
Function Signature:
function calculateTotalCoveredLength(intervals: number[][]): number
intervals: An array of arrays, where each inner array [start, end] represents a time interval. start and end are non-negative integers representing time points. It is guaranteed that start <= end for all intervals.intervals array is empty, the total covered length should be 0.[s, e], the covered length is e - s.start and end values are non-negative integers. The difference end - start will also be non-negative.Examples
Example 1
Input:
intervals = [[1,3],[5,7]]
Output:
4
Note:
The intervals are [1,3] and [5,7]. They do not overlap. Total length = (3-1) + (7-5) = 2 + 2 = 4.
Example 2
Input:
intervals = [[1,5],[3,7]]
Output:
6
Note:
The intervals [1,5] and [3,7] overlap. Their union is [1,7]. Total length = 7-1 = 6.
Example 3
Input:
intervals = [[1,10],[3,7],[12,15],[13,16]]
Output:
13
Note:
Intervals [1,10] contains [3,7], so they merge to [1,10]. Intervals [12,15] and [13,16] overlap, merging to [12,16]. The total covered length is (10-1) + (16-12) = 9 + 4 = 13.
Constraints
0 <= intervals.length <= 10^40 <= start_i <= end_i <= 10^9 for each interval [start_i, end_i]end_i - start_i can be up to 10^9.number type in JavaScript/TypeScript).start > end will not occur).Loading editor...