<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,2,6,1]
<strong>Output:</strong> [2,1,1,0]
<strong>Explanation:</strong>
To the right of 5 there are <b>2</b> smaller elements (2 and 1).
To the right of 2 there is only <b>1</b> smaller element (1).
To the right of 6 there is <b>1</b> smaller element (1).
To the right of 1 there is <b>0</b> smaller element.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [-1]
<strong>Output:</strong> [0]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [-1,-1]
<strong>Output:</strong> [0,0]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        
        def mergeSort(l, r):  # against list nums, l and r are inclusive indices
            if l == r:
                return
            m = (l + r) // 2
            mergeSort(l, m)
            mergeSort(m+1, r)
            tmp = []
            
            p1, p2 = l, m+1
            while p1 <= m and p2 <= r:
                if N[p1][0] <= N[p2][0]:
                    tmp.append(N[p1])
                    R[N[p1][1]] += p2 - m - 1
                    p1 += 1
                    if p1 > m: # append the rest of the 2nd half
                        while p2 <= r:
                            tmp.append(N[p2])
                            p2 += 1
                        break
                else: # >
                    tmp.append(N[p2])
                    p2 += 1
                    if p2 > r:
                        while p1 <= m:
                            tmp.append(N[p1])
                            R[N[p1][1]] += p2 - m - 1
                            p1 += 1
                        break
            
            # copy tmp back to the list N
            for i in range(l, r+1):
                N[i] = tmp[i - l]
            
            
        n = len(nums)
        N = [[v, i] for i, v in enumerate(nums)]  # (value, index) pair
        R = [0] * n
        mergeSort(0, n-1)
        return R
    
    
50898