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.
Input: ([[0, 10]],)
Expected Output: 10
Explanation: A single interval [0,10) covers length 10.
Input: ([[1, 4], [2, 3]],)
Expected Output: 3
Explanation: [2,3) is nested inside [1,4); covered span is [1,4), length 3.
Input: ([[1, 2], [2, 4], [4, 5]],)
Expected Output: 4
Explanation: Half-open intervals touching at 2 and 4 form one contiguous span [1,5), length 4 — no double counting.
Input: ([[1, 3], [5, 7], [5, 7], [1, 3]],)
Expected Output: 4
Explanation: Duplicates: [1,3) (length 2) and [5,7) (length 2), each counted once. Total 4.
Input: ([[-5, -1], [-3, 2], [10, 12]],)
Expected Output: 9
Explanation: [-5,-1) and [-3,2) merge into [-5,2) (length 7); [10,12) adds 2. Total 9, with negative coordinates.
Input: ([[3, 3], [1, 5]],)
Expected Output: 4
Explanation: [3,3) is zero-length and contributes nothing; covered span is [1,5), length 4.
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.