Compute total covered interval length
Company: LinkedIn
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: Compute total covered interval length evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= number of intervals <= 10^5
- Each interval is [l, r) with l <= r (l == r is a valid zero-length interval contributing 0)
- Coordinates may be negative; -10^9 <= l, r <= 10^9
- Intervals may overlap, be nested, or be exact duplicates
Examples
Input: ([[1, 3], [2, 5], [7, 9]],)
Expected Output: 6
Explanation: [1,3) and [2,5) merge into [1,5) (length 4); [7,9) adds 2. Total 6.
Input: ([],)
Expected Output: 0
Explanation: No intervals, so nothing is covered.
Hints
- Sort the intervals by their start coordinate, then sweep left to right keeping one 'current' merged span.
- Since the intervals are half-open [l, r), an interval whose start equals the current end (l == cur_r) still merges into the same contiguous span — use `l <= cur_r` as the overlap test.
- Drop zero-length intervals (l == r) up front, and only add the current span's length to the total when the next interval starts a fresh, non-overlapping span.
- Coordinate compression plus a segment tree gives an alternative that also supports incremental add/remove, but for a one-shot static query the O(n log n) line sweep is simplest.