https://leetcode.com/problems/count-of-smaller-numbers-after-self/?tab=Description

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

#### cpp

https://discuss.leetcode.com/topic/31288/c-o-nlogn-time-o-n-space-mergesort-solution-with-detail-explanation

C++ O(nlogn)-Time O(n)-Space MergeSort Solution with Detail Explanation

MergeSort-based solution is a standard way to solve problems related to inverse numbers.

Here is an example to illustrate the general idea of MergeSort-based algorithm:

Now we want to consider an array

First thing first, split the array into to subarrays:

and then calculate the inverse numbers within the group:

where the numbers in the parentheses are the numbers that should be counted when we calculate the inverse number.
Now we need to merge these two arrays into one sorted array. The first element to be put into the sorted destination array is the “1” in the first array.

The second element to merge is the “2” in the second array:

The third element to merge is the “4” in the first array:

When we merge the “4(1)”, we found that “4” is actually greater than all merged elements in the second array (i.e. [2]). Therefore, we also need to consider those elements. Therefore, the numbers in the parenthese of 2 become (1)+(2) = (1,2). Next step:

Next (add the inverse number of element “6” by 2)

So and so forth, finally reach

Additionally, when we need to count the inverse number, we do not need to record the exact elements, we only need to record the numbers. So, we can use a variable to record the number of “merged elements in the 2nd array” (for example, semilen in the code beneath) and the number of smaller elements of each element (for example, results[idx] in the code beneath).

Complexities:

Time: O(n log n)

Space: O(n)

C++ Accepted Code:

https://discuss.leetcode.com/topic/31291/c-short-solution-using-binary-indexed-tree-56-ms

C++ short solution using binary indexed tree (56 ms)

https://discuss.leetcode.com/topic/36736/c-14-line-solution

C++ 14 line solution

#### python

https://discuss.leetcode.com/topic/31162/mergesort-solution

Mergesort solution

The smaller numbers on the right of a number are exactly those that jump from its right to its left during a stable sort. So I do mergesort with added tracking of those right-to-left jumps.

Update, new version

Old version

https://discuss.leetcode.com/topic/33908/3-ways-segment-tree-binary-indexed-tree-binary-search-tree-clean-python-code

3 ways (Segment Tree, Binary Indexed Tree, Binary Search Tree) clean python code

Segment Tree

Binary Search Tree

#### java

10ms, 80.82%, October 18, 2016