1330. Small-Value Inversions

Medium3.5 points estimatedCounting SortArrayCountingPrefix Sum

A sensor network reports a signal level between 0 and 20 every millisecond and stores the readings in the array nums. To measure how jumpy the signal is, count the inversions: pairs of positions i < j where nums[i] is strictly greater than nums[j]. Equal readings never count, and each pair of positions is counted once, even if the same values appear elsewhere in the array.

Return the number of inversions as a 64-bit integer, because it can reach about 2 * 10^10. Since the levels are tiny, avoid the generic O(n log n) merge approach: keep a running count for each of the 21 levels and, for each new reading, add how many earlier readings were larger. That gives O(21 * n) time and O(1) extra space.

Example 1

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

The pairs (3, 1) and (3, 2) are out of order, so the count is 2.

Example 2

Input:
nums = [5,5,5]
Output:
0
Explanation:

Equal values never form an inversion, so the count is 0.

Example 3

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

A strictly decreasing array of length 4 has every one of the 6 pairs inverted.

Constraints

  • 1 ≤ n ≤ 2 * 105, where n is the length of nums
  • 0 ≤ nums[i] ≤ 20

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,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(1)

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…