-1

Hi I'm having difficulty solving this problem in O(N) time.

The input consists of N integers of values between 1 - 10^9 and the output should determine if it is possible to form a triangle using any 3 of the values given. The limits of N reach to 10^8 so I the solution has to run in O(N) time.

So i know about the triangle inequality but using the inequality to compare all the numbers will take run in O(NC3) time which will exceed the complexity allowed? Can I get some help on the correct solution?

1 Answers1

3

The triangle inequality states:

the sum of the lengths of any two sides of a triangle must be greater than or equal to the length of the third side.

Which implies this:

the sum of lengths of the shortest two sides must be greater than or equal to the length of the longest side.

So we take our (sorted) integers in turn, and compare it against the sum of the previous two integers. If they satisfy the inequality, then we've found a triangle. If they don't satisfy it, then we know that there's no smaller pair that would have satisfied it either.

This process is O(N), but it requires the list to be sorted. In general, sorting runs in O(N log N), but given you have integers with a finite domain you could theoretically use counting sort in O(N) (at the expense of O(N) memory).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680