1252. Exactly K Coverage Length

A paint crew marks stripes along a very long fence measured in millimetres. Each entry of intervals is a pair [a, b] describing one stripe that covers the real segment from min(a, b) to max(a, b); the two ends may come in either order, and a stripe with a == b covers nothing. Given intervals and an integer k, return the total length of fence that is covered by exactly k stripes.

Stripes may overlap, nest or repeat, and two stripes that only touch at a point add no length. Return the answer as a 64-bit integer. Aim for O(n log n) time and O(n) extra space: record +1 at each left end and -1 at each right end in a map, then sweep the sorted coordinates while keeping a running cover count.

Example 1

Input:
intervals = [[1,4],[2,6],[5,9]], k = 2
Output:
3
Explanation:

Cover is 1 on [1,2), 2 on [2,4), 1 on [4,5), 2 on [5,6) and 1 on [6,9); the exactly-2 parts have length 2 + 1 = 3.

Example 2

Input:
intervals = [[0,10],[10,0],[3,3]], k = 2
Output:
10
Explanation:

The first two stripes are the same segment [0,10] given in opposite order and the third has zero length, so exactly two stripes cover length 10.

Example 3

Input:
intervals = [[5,8],[1,2]], k = 1
Output:
4
Explanation:

The stripes [1,2] and [5,8] are disjoint, so the length covered exactly once is 1 + 3 = 4.

Constraints

1 ≤ n ≤ 1000 where n = intervals.length; 0 ≤ a, b ≤ 109; 1 ≤ k ≤ n; the answer fits in a 64-bit integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…