Here is the interview question prompt, presented for reference.
This was submitted by user Hackleman.
Determine how "out of order" a list is by writing a function that returns the number of inversions in that list.
Two elements of a list L, L[i] and L[j], form an inversion if L[i] < L[j] but i > j.
For example, the list [5, 4, 3, 2, 1] has 10 inversions since every element is out of order. They are the following: (5, 4), (5,3), (5,2), (5,1), (4,3), (4,2), (4,1), (3,2), (3,1), (2,1).
The list [2, 1, 4, 3, 5] has two inversions: (2, 1) and (4, 3).
Do this in better than O(N^2).
100000-1000000000 to 1000000000O(nlogn)O(1)You can see the full challenge with visuals at this link.
Challenges • Asked almost 6 years ago by Anonymous
This is the main discussion thread generated for How Out Of Order.
It would be helpful to describe the inversions in the first example:
(5,4) (5,3) (5,2) (5,1)
(4,3) (4,2) (4,1)
(3,2) (3,1)
(2,1)
Yes, great point! Added.
The given is the first element of list instead of list. The result of below console printout:
function inversions(list) {
console.log(list);
...
5
AssertionError: expected 0 to equal 10
2
AssertionError: expected 0 to equal 3
Hello there... test function should be inversions not inversion...