Skip to the content

Pairs out of order

Problem

Write a function that takes a list of numbers and returns how many pairs sit the other way round from how they would sit if the list were sorted from smallest to largest. A pair is the other way round when one number is bigger than another number that shows up after it.

With 1, 20, 6, 4 and 5 the answer is 5: 20 is bigger than 6, than 4 and than 5, and 6 is bigger than 4 and than 5.

The two extremes tell you whether you are on track: a list that is already sorted from smallest to largest has no pair the other way round, and one sorted from largest to smallest has every pair.

The rules: the two numbers don't have to sit next to each other, count the far apart ones too. Two equal numbers are not the other way round, so they don't count. With an empty list, or one with a single number, there is no pair to check and the answer is 0.

A hint: compare each number with every number that comes after it and keep a tally.

Examples

  • The example

    [1, 20, 6, 4, 5] → 5

  • Already sorted

    [1, 2, 3, 4] → 0

  • Largest to smallest

    [4, 3, 2, 1] → 6

  • One that slips in

    [1, 2, 1] → 1

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def reversed_pairs(data):
    pass

JavaScript

function reversedPairs(data) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →