Question

You are given a set of n numbers. Give an O(n^2) algorithm (NOT O(n^3), O(n^2)) to...

You are given a set of n numbers. Give an O(n^2) algorithm (NOT O(n^3), O(n^2)) to decide if there exist three numbers a, b and c are in the set such that a + b = c

(Hint: sort the numbers first).

0 0
Add a comment Improve this question Transcribed image text
Answer #1

`Hey,

Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.

Efficient approach : The idea is similar to Find a triplet that sum to a given value.

  • Sort the given array first.
  • Start fixing the greatest element of three from back and traverse the array to find other two numbers which sum upto the third element.
  • Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers
  • If the addition of both the numbers is still less than A[i], then we need to increase the value of the summation of two numbers, thereby increase the j pointer, so as to increase the value of A[j] + A[k].
  • If the addition of both the numbers is more than A[i], then we need to decrease the value of the summation of two numbers, thereby decrease the k pointer so as to decrease the overall value of A[j] + A[k].

Below is the algorithm in coding style

sort(a); // non-descending
for (i = 0; i < n; i++) {
  j = i; k = i + 1;
  while (j < n && k < n) {
    if (a[i] + a[j] == a[k])
      return true;
    else if (a[i] + a[k] < a[j])
      k++;
    else
      j++;
  }
}
return false;

Since there are 2 nested loops involved. So, it is O(n^2)

Time complexity: O(N^2)

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
You are given a set of n numbers. Give an O(n^2) algorithm (NOT O(n^3), O(n^2)) to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT