1306. Calm Stretch Length Histogram

Given readings in the array nums and a number limit, call a subarray calm when its maximum minus its minimum is at most limit. Return an array h of length n where h[L - 1] is the number of calm subarrays of exactly length L, for every L from 1 to n. Every contiguous part of a calm subarray is also calm, so for each right end only the smallest calm left boundary has to be found, using two monotonic deques; all lengths from 1 up to that window size are then counted at once with a difference array. Counts fit in 32-bit integers. Target O(n) time and O(n) space.

Example 1

Input:
nums = [3,1,2], limit = 1
Output:
[3,1,0]
Explanation:

All three single readings are calm, only the pair [1, 2] has a spread within 1, and the whole array has spread 2, so h is [3, 1, 0].

Example 2

Input:
nums = [7,7,7], limit = 0
Output:
[3,2,1]
Explanation:

Every subarray of equal readings is calm: three of length 1, two of length 2 and one of length 3.

Example 3

Input:
nums = [1,5,2], limit = 3
Output:
[3,1,0]
Explanation:

Singles are calm, the pair [5, 2] has spread 3 so it is calm, [1, 5] has spread 4 so it is not, and the whole array has spread 4, giving [3, 1, 0].

Constraints

1 ≤ n ≤ 2*105

0 ≤ nums[i] ≤ 109

0 ≤ limit ≤ 109

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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O(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…