1366. Window Disorder Counts

A sensor reports one reading per second, stored in the array nums. An analyst looks at every window of exactly k consecutive readings, and measures its disorder as the number of pairs of positions p < q inside the window with nums[p] > nums[q]. Equal readings are not disordered.

Return an array of length n - k + 1 whose entry i is the disorder of the window that starts at index i, as longs. Recomputing every window from scratch is too slow. Slide a Fenwick tree over the compressed values: when the left element leaves, subtract how many smaller values remain in the window, and when a new element enters, add how many larger values are already there. Aim for O(n log n) time and O(n) space.

Example 1

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

The windows [3,1,2], [1,2,5] and [2,5,4] contain 2, 0 and 1 out-of-order pairs, so the answer is [2, 0, 1].

Example 2

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

There is a single window and it is already ascending, so the answer is [0].

Example 3

Input:
nums = [2,2,2], k = 2
Output:
[0,0]
Explanation:

Equal readings never form an out-of-order pair, so both windows have disorder 0.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 105

  • -109 ≤ nums[i] ≤ 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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 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…