<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 {
public:
    void merge(vector<vector<int>>& nums, int start, int mid, int end, vector<vector<int>>& aux) {
        for(int i = start; i <= end; i++) {
            aux[i] = nums[i];
        }

        int inversion_count_per_element = 0;
        int index1 = start, index2 = mid + 1;

        for (int index = start; index <= end; index++) {
            if (index1 > mid) {
                nums[index] = aux[index2++];
            }
            else if (index2 > end || aux[index1][0] <= aux[index2][0]) {
                nums[index] = aux[index1++];
                nums[index][2] += inversion_count_per_element;
            }
            else {
                nums[index] = aux[index2++];
                inversion_count_per_element++;
            }
        }
    }
    void merge_sort(vector<vector<int>>& nums, int start, int end, vector<vector<int>>& aux) {
        if (start < end) {
            int mid = (start + end) / 2;
            merge_sort(nums, start, mid, aux);
            merge_sort(nums, mid + 1, end, aux);
            merge(nums, start, mid, end, aux);
        }
    }
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        vector<vector<int>> nums_copy, aux;

        for (int i = 0; i < n; i++) {
            nums_copy.push_back({nums[i], i, 0});
            aux.push_back({nums[i], i, 0});
        }

        merge_sort(nums_copy, 0, n - 1, aux);

        vector<int> counts(n, 0);
        for (int i = 0; i < n; i++) {
            counts[nums_copy[i][1]] = nums_copy[i][2];
        }
        return counts;
    }
};
216131