<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]:
        # merge sort will have left and right subarrays, that items in the right might be inserted before items left array
        # such operation is equivalent to this question
        # reference: 
        # https://leetcode.com/problems/count-of-smaller-numbers-after-self/solutions/445769/merge-sort-clear-simple-explanation-with-examples-o-n-lg-n/

        # CAREFUL: do not use defaultdict(int)
        # there are DUPLICATED entry in the nums!!
        counts = [0 for _ in range(len(nums))]

        def merge_sort(start, end):
            if end - start == 1:  # Base case: return an array of (num, index)
                return [(nums[start], start)]
            
            mid = (start + end) // 2
            left = merge_sort(start, mid)
            right = merge_sort(mid, end)
            l = r = 0   # left right pointer to iterate through left, right array

            sorted_arr = []
            inversion_count = 0
            while l < len(left) and r < len(right):
                # check if the right number < left number
                if right[r][0] < left[l][0]:
                    inversion_count += 1
                    sorted_arr.append(right[r]) # append the right TUPLE
                    r += 1
                else:
                    counts[left[l][1]] += inversion_count
                    sorted_arr.append(left[l])
                    l += 1
            
            while l < len(left):
                counts[left[l][1]] += inversion_count
                sorted_arr.append(left[l])
                l += 1

            while r < len(right):
                sorted_arr.append(right[r])
                r += 1
            
            return sorted_arr
        
        merge_sort(0, len(nums))
        return counts
54925