[IMPORTANT]: Below is answer for initial question, where there is no condition that i < j
You can sort in O(N * log(N))
and then find an answer in O(N)
, It will give you O(N * log(N))
in total. Below is code of second part (after array is sorted):
int count = 0;
int curBefore = 0;
for (int i = 1; i < sorted.Length; i++)
{
if (sorted[i] > sorted[i - 1])
{
curBefore = i;
}
count += curBefore;
}
And yes, there is a linear (pseudo, because Dictionary operations are not linear in general case) solution too! But it needs additional memory and using of Dictionary-like data structure:
int res = sorted.Length * (sorted.Length - 1) / 2;
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < sorted.Length; i++)
{
if (!dict.ContainsKey(sorted[i]))
{
dict.Add(sorted[i], 0);
}
dict[sorted[i]]++;
}
foreach (var pair in dict)
{
res -= (pair.Value - 1) * pair.Value / 2;
}