1335. Rotation With Fewest Inversions

Medium3.5 points estimatedMerge SortArrayDivide and ConquerMaths

A carousel holds n numbered seats, and perm lists the seat numbers in the order the riders see them, as a permutation of 1 to n. An inversion is a pair of positions i < j with perm[i] > perm[j]. A left rotation moves the first element to the end of the array. Return the smallest inversion count among all n rotations of perm, including the unrotated array (zero rotations). The answer can exceed 32 bits, so return it as a 64-bit integer. Count the starting inversions once with merge sort, then update the count from one rotation to the next in O(1), giving O(n log n) time overall.

Example 1

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

The three rotations have 1, 1 and 3 inversions, so the minimum is 1.

Example 2

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

The unrotated array is sorted and has 0 inversions.

Example 3

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

Rotating once gives 2, 1, 3, which has a single inversion.

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…