How to know that a triangle triple exists in one array?

IT's just a mathematical derivation!!!!!!!!!!!!!!!!! 

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?

share improve this question
 
1 
(0, 2, 4) doesn't fit: 0 + 2 is not > 4. –  Vlad  Mar 22 '11 at 12:32
7 
He is mentioning the index numbers as the answer ... 10 , 5 , 8 –  user506710  Mar 22 '11 at 12:33 
 
Does the first condition refer to the values of P R Q or the Index? Because, if P < Q < R, than two elements would fail to satisfy this condition. However, on codility, an array of two elements can be a triplet. This does not make sense to me. –  Ray Suelzer  Dec 27 '14 at 2:08
 
How can this be mark as painless? –  jacktrades  Nov 19 '15 at 19:36 

9 Answers

up vote 43 down vote accepted

First of all, you can sort your sequence. For the sorted sequence it's enough to check that A[i] + A[j] > A[k] for i < j < k, because A[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 other A[k] are even bigger (so if the inequality holds for some k, it holds for k = j + 1 as well).

Next, it's enough to check that A[j-1] + A[j] > A[j+1], because other A[i] are even smaller (so if inequality holds for some i, it holds for i = 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] and A[k] form a triangle triple, then A[i] + A[j] > A[k]A[i] + A[k] > A[j], which implies 2 * A[i] + A[j] + A[k] > A[k] + A[j], hence 2 * A[i] > 0, so A[i] > 0 and by symmetry A[j] > 0A[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.

share improve this answer
 
5 
Nice job. [15chars] –  st0le  Mar 22 '11 at 12:56
 
@st0le: thanks! –  Vlad  Mar 22 '11 at 13:09
 
Thanks for sharing the idea Vlad. This really helps to break down the problem into an easier task. Thanks ! –  all_by_grace  Mar 22 '11 at 15:19
4 
@useless: Nope. Obviously if a triple exists in the sorted array, it must exist in the original array (just map the indices back and sort them). You can see that the problem is symmetric w.r.t. index swapping. –  Vlad  Apr 17 '13 at 10:11
1 
"it's enough to check that A[i] + A[j] > A[k] for i < j < k, because A[i] + A[k] > A[k]" If A[i] is negative, A[i] + A[k] < A[k] ... –  Chan Le  Feb 26 '14

Count the number of possible triangles

Given an unsorted array of positive integers. Find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values, the sum of any two values (or sides) must be greater than the third value (or third side).
For example, if the input array is {4, 6, 3, 7}, the output should be 3. There are three triangles possible {3, 4, 6}, {4, 6, 7} and {3, 6, 7}. Note that {3, 4, 7} is not a possible triangle.
As another example, consider the array {10, 21, 22, 100, 101, 200, 300}. There can be 6 possible triangles: {10, 21, 22}, {21, 100, 101}, {22, 100, 101}, {10, 100, 101}, {100, 101, 200} and {101, 200, 300}

We strongly recommend that you click here and practice it, before moving on to the solution.


Method 1 (Brute force)
The brute force method is to run three loops and keep track of the number of triangles possible so far. The three loops select three different values from array, the innermost loop checks for the triangle property ( the sum of any two sides must be greater than the value of third side).

Time Complexity: O(N^3) where N is the size of input array.

Method 2 (Tricky and Efficient)
Let a, b and c be three sides. The below condition must hold for a triangle (Sum of two sides is greater than the third side)
i) a + b > c
ii) b + c > a
iii) a + c > b

Following are steps to count triangle.

1. Sort the array in non-decreasing order. 

2. Initialize two pointers ‘i’ and ‘j’ to first and second elements respectively, and initialize count of triangles as 0.

3. Fix ‘i’ and ‘j’ and find the rightmost index ‘k’ (or largest ‘arr[k]’) such that ‘arr[i] + arr[j] > arr[k]’. The number of triangles that can be formed with ‘arr[i]’ and ‘arr[j]’ as two sides is ‘k – j’. Add ‘k – j’ to count of triangles. 

Let us consider ‘arr[i]’ as ‘a’, ‘arr[j]’ as b and all elements between ‘arr[j+1]’ and ‘arr[k]’ as ‘c’. The above mentioned conditions (ii) and (iii) are satisfied because ‘arr[i] < arr[j] < arr[k]'. And we check for condition (i) when we pick 'k'4. Increment ‘j’ to fix the second element again. 

Note that in step 3, we can use the previous value of ‘k’. The reason is simple, if we know that the value of ‘arr[i] + arr[j-1]’ is greater than ‘arr[k]’, then we can say ‘arr[i] + arr[j]’ will also be greater than ‘arr[k]’, because the array is sorted in increasing order.

5. If ‘j’ has reached end, then increment ‘i’. Initialize ‘j’ as ‘i + 1′, ‘k’ as ‘i+2′ and repeat the steps 3 and 4.

Following is implementation of the above approach.

  • C/C++
  • Java
  • Python
# Python function to count all possible triangles with arr[]
# elements
 
def findnumberofTriangles(arr):
 
     # Sort array and initialize count as 0
     n = len (arr)
     arr.sort()
     count = 0
 
     # Fix the first element.  We need to run till n-3 as
     # the other two elements are selected from arr[i+1...n-1]
     for i in range ( 0 ,n - 2 ):
 
         # Initialize index of the rightmost third element
         k = i + 2
 
         # Fix the second element
         for j in range (i + 1 ,n):
 
             # Find the rightmost element which is smaller
             # than the sum of two fixed elements
             # The important thing to note here is, we use
             # the previous value of k. If value of arr[i] +
             # arr[j-1] was greater than arr[k], then arr[i] +
             # arr[j] must be greater than k, because the array
             # is sorted.
             while (k < n and arr[i] + arr[j] > arr[k]):
                 k + = 1
 
              # Total number of possible triangles that can be
              # formed with the two fixed elements is k - j - 1.
              # The two fixed elements are arr[i] and arr[j]. All
              # elements between arr[j+1] to arr[k-1] can form a
              # triangle with arr[i] and arr[j]. One is subtracted
              # from k because k is incremented one extra in above
              # while loop. k will always be greater than j. If j
              # becomes equal to k, then above loop will increment k,
              #  because arr[k] + arr[i] is always greater than arr[k]
             count + = k - j - 1
 
     return count
 
# Driver function to test above function
arr = [ 10 , 21 , 22 , 100 , 101 , 200 , 300 ]
print "Number of Triangles:" ,findnumberofTriangles(arr)
 
# This code is contributed by Devesh Agrawal


Output:
Total number of triangles possible is 6

Time Complexity: O(n^2). The time complexity looks more because of 3 nested loops. If we take a closer look at the algorithm, we observe that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of outer most loop, because k starts from i+2 and goes upto n for all values of j. Therefore, the time complexity is O(n^2).


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值