1506. Fewest Parallel Ovens

Hard7.5 points estimatedBinary SearchHeapGreedySorting

A bakery receives n orders. Order i is given as jobs[i] = [release, deadline]: it needs exactly one time slot of baking, and that slot must be an integer t with release <= t <= deadline. An oven bakes one order per slot, and several ovens can run in the same slot. Orders are independent and may be baked in any order.

Return the minimum number of ovens m for which every order can be assigned a valid slot, with no slot holding more than m orders. Hint: the answer is monotone in m, so binary search it. To test one value, sweep the slots in time order, keep the orders already released in a min-heap keyed by deadline, bake up to m earliest-deadline orders per slot, and jump straight to the next release when the heap is empty. Aim for O(n log n log n) time and O(n) space.

Example 1

Input:
jobs = [[1,2],[1,2],[1,2],[1,2]]
Output:
2
Explanation:

Four orders share only slots 1 and 2, so at least two ovens are needed and two suffice.

Example 2

Input:
jobs = [[0,0]]
Output:
1
Explanation:

A single order needs a single oven.

Example 3

Input:
jobs = [[1,1],[2,2],[3,3]]
Output:
1
Explanation:

The orders have disjoint windows, so one oven bakes them one after another.

Constraints

1 ≤ n ≤ 1000

0 ≤ release ≤ deadline ≤ 109

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^2 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…