DVCQ-P3

Smaller values to the right

Practice 3 of 6Divide and conquer8 tests

The problem

For every position i of a list of numbers, count the positions j > i with values[j] < values[i]. Return the counts as a list of the same length.

smaller_after([5, 2, 6, 1])   # [2, 1, 1, 0]
smaller_after([3, 3, 3])      # [0, 0, 0]: equal is not smaller

The counts add up to the number of inversions of the list (lesson 3). The values may be negative and may repeat.

Limits

  • Up to 200,000 values, in any order, including an order that is already sorted. Aim for O(n log n).

Builds on DVCQ-3 Counting inversions.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No valuesNot run
3One valueNot run
4All equalNot run
5FallingNot run
6Repeats and negativesNot run
7Already in order, 200,000 valuesNot run
8120,000 scattered valuesNot run