Ques : Find number of inversion counts in Range [L,R] for Q queries. ****
Array Size <=1000 ; Each integer from 1 to n occurs exactly once in this array.
Queries<= 100000
What is the best method you can suggest? Any help is much appreciated.
Thanks :)
I think this can be done without a log factor in $$$O(n^2 + Q)$$$. Create a 2D array such that
arr[l][r]
gives us whether $$$A_l>A_r$$$ and $$$l<r$$$. Use prefix sums to calculate the inversions. It will just be the sum ofarr[i][j]
where $$$i$$$ and $$$j$$$ satisfy $$$l\le i \le r$$$ and $$$l\le j \le r$$$.If I understand correctly, it works in $$$O(n^2 + Q\cdot n)$$$, because you need to iterate over $$$[l ... r)$$$.
2D prefix sums can also be done in $$$O(1)$$$. Here's a simple implementation
Now you can get 2D prefix sum for $$$a\le i \le b$$$ and $$$c \le j \le d$$$ by doing
gridsum[b][d] - gridsum[b][c-1] - gridsum[a-1][d] + gridsum[a-1][c-1]
You are correct, nice catch.
Can you please provide the problem link ?
Here's what you're looking for https://www.youtube.com/watch?v=kPaJfAUwViY&t=1456s (fenwick tree solution)