People join a ticket queue in order and get tickets 1, 2, …, n, front to back. While waiting, a person may overtake the person directly in front of them, swapping places. Each person overtakes at most twice; being overtaken does not count against you.
Given the final queue, front to back, as the array order:
countOvertakes(order) returns the fewest overtakes that turn 1, 2, …, n into order, or -1 if it cannot be reached without someone overtaking more than twice.
overtakesByPerson(order) returns an array whose entry p - 1 is how many times ticket p overtook in a fewest-overtakes sequence, or null if the order cannot be reached. (In every fewest-overtakes sequence each out-of-order pair swaps exactly once, so these numbers are the same for all of them.)
Rules:
An empty queue returns 0 and [].
If order is not an array containing each of the integers 1 to n exactly once, throw a TypeError.
Queues can hold 200,000 people. Comparing every pair of people is quadratic and will not finish in time.