<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]:
        # A modified version of count inversion.
        # [(v, i), forall i]

        def _helper(left, right):
            if left == right:
                return [(nums[left], left, 0)]
            
            mid = (left + right) // 2
            left_sorted = _helper(left, mid)
            right_sorted = _helper(mid + 1, right)

            final_merged = []

            l_pt, r_pt = 0, 0

            while l_pt < len(left_sorted) and r_pt < len(right_sorted):
                if left_sorted[l_pt][0] <= right_sorted[r_pt][0]:
                    final_merged.append((left_sorted[l_pt][0], left_sorted[l_pt][1], left_sorted[l_pt][2] + r_pt))
                    l_pt += 1
                else:
                    final_merged.append(right_sorted[r_pt])
                    r_pt += 1
            
            while l_pt < len(left_sorted):
                final_merged.append((left_sorted[l_pt][0], left_sorted[l_pt][1], left_sorted[l_pt][2] + r_pt))
                l_pt += 1
            
            while r_pt < len(right_sorted):
                final_merged.append(right_sorted[r_pt])
                r_pt += 1
            
            return final_merged
        
        final = _helper(0, len(nums) - 1)

        ans = [0 for _ in range(len(nums))]
        for _, i, c in final:
            ans[i] = c
        return ans




57162