Count inversions with merge sort
Return the number of index pairs with i less than j and items[i] greater than items[j], leaving input unchanged. Equal values are not inversions. Use O(n log n) time.
left = [2, 4, 7]
right_value, consumed = 1, 0
print(len(left)-consumed) # new inversionsReason about the state
During merge, taking a smaller right value creates an inversion with every unconsumed left value. Count these while recursively sorting both halves. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return the number of index pairs with i less than j and items[i] greater than items[j], leaving input unchanged. Equal values are not inversions. Use O(n log n) time.
The explanation opens here once every check passes.