<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 add(int index,int low,int high,int update_index,vector<int>&tree){
    if(low==high) {
        tree[index]++;
        return ;
    }
    
   int mid=low+(high-low)/2;
    if (update_index <= mid) {
            add(2 * index + 1, low, mid, update_index, tree);
        } else {
            add(2 * index + 2, mid + 1, high, update_index, tree);
        }
     tree[index]=tree[2*index+1]+tree[2*index+2];



}

int get(int index,int low,int high,int l,int r,vector<int>&tree){
    if(high<l||low>r) return 0;
    if(low>=l&&high<=r) return tree[index];
    int mid=low+(high-low)/2;
    return get(2*index+1,low,mid,l,r,tree)+get(2*index+2,mid+1,high,l,r,tree);

}
    vector<int> countSmaller(vector<int>& nums) {
        //first method using segmented tree
        /*because values can be negative so we add 10001 in it so it becomes 1 based indexing as we know if 1<8 the 1+10<8+10*/
     vector<int>tree(4*1e6,0);

        vector<int>ans;
        for(int i=nums.size()-1;i>=0;i--){
            int val=nums[i]+10001;
            ans.push_back(get(0,0,1e6-1,0,val-1,tree));
            add(0,0,1e6-1,val,tree);
        }

reverse(ans.begin(),ans.end());
  return ans;  }
};
321881