Given a set integers, the problem consists of finding the number of possible arithmetic series of length 3. The set of integers may or may not be sorted.
I could implement a simple bruteforce algorithm taking time O(n^3) but time efficiency is important and the set of integers can be as large as 10^5. This means bruteforce obviously won’t work. Can anyone suggest some algorithm/pseudocode/code in c++?
An example: there are 4 numbers 5,2,7,8 . Clearly there is only one such possibility – (2,5,8) in which the common difference is 3, so our answer is 1.
EDIT:I forgot to mention one important property – each number of set given is between 1 to 30000 (inclusive).
You can do it in O(N^2) as follows: create a hash set of your integers so that you could check a presence or absence of an element in
O(1). After that, make two nested loops over all pairs of set elements{X, Y}. This is done inO(N^2).For each pair
{X, Y}, assume thatX < Y, and calculate two numbers:A triple
{X, Y, Zi}form an arithmetic sequence ifZi != X && Zi != Y && set.contains(Zi)Check both triples
{X, Y, Z1}and{X, Y, Z2}. You can do it inO(1)using a hash set, for a total running time of the algorithm ofO(N^2).