.
Let $X \in \mathbb{Z}^n$. I need to find the number of pairs $ (i, j)$ with $ 0 < i < j \le n$ such that $ X_i>X_j$ as well as the number of pairs $ (i, j),\ 0 < i < j \le n$, such that $ X_i=X_j$.
I know how to calculate in $O(n \log(n))$ time complexity. How to prove that a comparison-based algorithm with better complexity does not exist (check "update" section on the bottom)?
An algorithm with $O(n log(n))$ time complexity (one of the known methods):
We store:
1) 2 accumulators for the first and for the second value. (both of them initially 0)
2) Balanced search tree (AVL, for example) with the size of subtree at each vertex (operation "add element" is $O(\log \text{size})$ cost). Elements in this tree are 2-tuples $((-\infty\cup\mathbb{Z}\cup\infty), \mathbb{Z} )$, comparison is done by first element, if first elements are equal - by the second element. Initially this tree is empty.
Subprocedure - find the number of elements in the tree that lay in the interval $[X, Y]$ - with the time cost $O(\log n)$ (trivial)
Call this procedure as count$(X, Y)$
So, for $i$ from $1$ to $n$:
- add to first accumulator count( ($-\infty,1$),($X_i -1, i$))
- add to second accumulator count (($X_i -1, -1$), ($X_i -1, i-1$))
- add to balanced tree ($X_i, i$)
So, $n$ steps with $O (\log{n})$ cost
Update: It cannot be calculated faster than $O(n)$ complexity: The second count can be calculated with $O(n)$ time complexity (with the simple hash tables), so I need to prove the time complexity lower bound only for counting the pairs $ (i, j),\ 0 < i < j \le n$ such that $X_i>X_j$