1752. Longest Board After Cuts

Medium3.5 points estimatedOrdered SetHeapArray

A carpenter lays a plank along a measuring rail from position 0 to position length. The carpenter then makes saw cuts one after another at the integer positions listed in cuts; a cut at a position that has already been cut changes nothing. After each cut, the carpenter wants to know how long the longest remaining piece is. Return an array ans with the same length as cuts, where ans[i] is the length of the longest piece after the first i + 1 cuts have been made. Every cut lies strictly between 0 and length. A solution running in O(n log n) time and O(n) space is expected, where n is the number of cuts. There are up to 10^5 cuts and length is at most 10^9.

Example 1

Input:
length = 10, cuts = [4,7,2]
Output:
[6,4,3]
Explanation:

After cutting at 4 the pieces are 4 and 6; cutting at 7 leaves 4, 3 and 3; cutting at 2 leaves 2, 2, 3 and 3, so the answers are 6, 4, 3.

Example 2

Input:
length = 8, cuts = [4,4,4]
Output:
[4,4,4]
Explanation:

Cutting at 4 splits the plank into 4 and 4; repeating the same cut changes nothing, so every answer is 4.

Constraints

1 ≤ cuts.length ≤ 105; 2 ≤ length ≤ 109; 0 < cuts[i] < length.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

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…