<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 Seg{
    vector<int>seg;
public:
    Seg(int n){
        seg.resize(n*4, 0);
    }

    void update(int l, int r, int idx, int pos, int val){
        if(l==r){
            seg[idx] = val;
            return;
        }

        int m = (l+r)/2;
        if(pos<=m){
            update(l, m, idx*2, pos, val);
        }
        else{
            update(m+1, r, idx*2+1, pos, val);
        }

        seg[idx] = seg[idx*2] + seg[idx*2+1];
    }

    int q(int l, int r, int idx, int x, int y){
        if(y<l || r<x){
            return 0;
        }
        if(x<=l and r<=y){
            return seg[idx];
        }

        int m = (l+r)/2;
        int left = q(l, m, idx*2, x, y);
        int right = q(m+1, r, idx*2+1, x, y);

        return left+right;
    }
};

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {
        vector<pair<int,int>>val_and_idx;
        int n = nums.size();
        Seg seg(n);

        for(int i=0; i<n; i++){
            val_and_idx.emplace_back(nums[i], i);
        }

        sort(val_and_idx.begin(), val_and_idx.end());
        map<pair<int,int>, int>position;

        for(int i=0; i<n; i++){
            position[val_and_idx[i]] = i;
        }

        vector<int>ans(n);
        for(int i=n-1; i>=0; i--){
            int idx = position[{nums[i], i}];
            
            int val = seg.q(0, n-1, 1, 0, idx);
            seg.update(0, n-1, 1, idx, 1);

            ans[i] = val;
        }

        return ans;
    }
};
152681