I was stuck in solving the following interview practice question:
I have to write a function:
int triangle(int[] A);
that given a zero-indexed array A consisting of N
integers returns 1
if there exists a triple (P, Q, R) such that 0 < P < Q < R < N
.
A[P] + A[Q] > A[R],
A[Q] + A[R] > A[P],
A[R] + A[P] > A[Q].
The function should return 0
if such triple does not exist. Assume that 0 < N < 100,000
. Assume that each element of the array is an integer in range [-1,000,000..1,000,000]
.
For example, given array A
such that
A[0]=10, A[1]=2, A[2]=5, A[3]=1, A[4]=8, A[5]=20
the function should return 1
, because the triple (0, 2, 4)
fulfills all of the required conditions.
For array A
such that
A[0]=10, A[1]=50, A[2]=5, A[3]=1
the function should return 0
.
If I do a triple loop, this would be very very slow (complexity: O(n^3)
). I am thinking maybe to use to store an extra copy of the array and sort it, and use a binary search for a particular number. But I don't know how to break down this problem.
Any ideas?
I have got another solution to count triangles. Its time complexity is O(N**3) and takes long time to process long arrays.
Here's my solution in C#, which gets 90% correctness (the wrong answer is returned for test
extreme_arith_overflow1 -overflow test, 3 MAXINTs-
) and 100% performance.In Java:
First of all, you can sort your sequence. For the sorted sequence it's enough to check that
A[i] + A[j] > A[k]
fori < j < k
, becauseA[i] + A[k] > A[k] > A[j]
etc., so the other 2 inequalities are automatically true.(From now on,
i < j < k
.)Next, it's enough to check that
A[i] + A[j] > A[j+1]
, because otherA[k]
are even bigger (so if the inequality holds for somek
, it holds fork = j + 1
as well).Next, it's enough to check that
A[j-1] + A[j] > A[j+1]
, because otherA[i]
are even smaller (so if inequality holds for somei
, it holds fori = j - 1
as well).So, you have just a linear check: you need to check whether for at least one
j
A[j-1] + A[j] > A[j+1]
holds true.Altogether
O(N log N) {sorting} + O(N) {check} = O(N log N)
.Addressing the comment about negative numbers: indeed, this is what I didn't consider in the original solution. Considering the negative numbers doesn't change the solution much, since no negative number can be a part of triangle triple. Indeed, if
A[i]
,A[j]
andA[k]
form a triangle triple, thenA[i] + A[j] > A[k]
,A[i] + A[k] > A[j]
, which implies2 * A[i] + A[j] + A[k] > A[k] + A[j]
, hence2 * A[i] > 0
, soA[i] > 0
and by symmetryA[j] > 0
,A[k] > 0
.This means that we can safely remove negative numbers and zeroes from the sequence, which is done in
O(log n)
after sorting.The above implementation is Linear in time complexity. The concept is simple use the formaula they gave extracting a series of triplets of sorted elements.
A 100/100 php solution: http://www.rationalplanet.com/php-related/maxproductofthree-demo-task-at-codility-com.html