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?