I encountered the problem in a programming interview and have no idea about it by now.
A list whose length is n, the elements in it are all positive integers without order.
To find out all possible triples (a, b, c), that a < b < c, and a appears before b and b before c in the list.And analyse the time complexity of your algorithm.
If it is known that there are only a small set of triples (say k), then you may prefer to find all the triples by storing pointers to the previous smallest element.
ALGORITHM
Prepare an empty data structure (possible choices described later).
Prepare an empty array B of length n.
Then for each element c in the list:
DATA STRUCTURE
The data structure needs to be able to store value,position pairs to make it easy to find the largest position (i.e. most recent) over all elements with value less than c.
One easy way to do this if the range of allowed values is fairly small is to use a series of arrays where A[k][x] stores the maximum position for all elements in the range [x*2^k,(x+1)*2^k).
If the values have up to M bits (i.e. the values are in the range 0 to 2^M-1) then updating or accessing this data structure are both O(M) operations.
COMPLEXITY
The given method is O(nM+k).
If the values have a larger range, then you could use a form of binary search tree instead of the series of arrays, or instead sort the values and replace the values with their ordinal value. This would then have complexity O(nlogn+k).
COUNTING TRIPLES
If you just wish to know the total number of triples of this form then you can do this in O(n).
The idea is similar to before:
To make this O(n) we need to be able to find the next greater element in O(n). This can be done by:
We also need to be able to find the count of greater elements in O(n). Once the NGE array has been prepared, we can find the counts by iterating backwards over the array and computing
The most recent smaller elements and counts can be computed in an analogous way.