1351. Far Inversion Count

Medium3.5 points estimatedMerge SortArrayDivide and Conquer

A conveyor belt carries parcels labelled by the permutation perm of 1 to n. A pair of positions (i, j) is a far inversion when j - i >= 2 and perm[i] > perm[j], meaning two parcels at least two places apart are in the wrong order. Adjacent pairs never count, even when they are out of order. Return the number of far inversions as a 64-bit integer. Count all inversions with a merge sort and subtract the number of adjacent descents, for O(n log n) time and O(n) extra space.

Example 1

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

Only the pair at positions 0 and 2 (values 3 and 2) is far apart and out of order; the adjacent descent 3, 1 does not count.

Example 2

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

The array is sorted, so there are no inversions at all.

Example 3

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

The far pairs are (4,2), (4,1) and (3,1), and the three adjacent descents are excluded.

Constraints

1 ≤ n ≤ 105

perm is a permutation of 1..n

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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,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…