Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all pairs (x, y) in a sorted array so that x + y < z

This is an interview question. Given a sorted integer array and number z find all pairs (x, y) in the array so that x + y < z. Can it be done better than O(n^2)?

P.S. I know that we can find all pairs (x, y | x + y == z) in O(N).

like image 641
Michael Avatar asked Sep 02 '12 07:09

Michael


2 Answers

You cannot necessarily find all such pairs in O(n) time, because there might be O(n2) pairs of values that have this property. In general, an algorithm can't take any less time to run than the number of values that it produces.

Hope this helps!

like image 136
templatetypedef Avatar answered Oct 01 '22 11:10

templatetypedef


In generate, no it can't. Consider the case where x + y < z for all x, y in the array. You have to touch (e.g. display) all of the n(n - 1)/2 possible pairs in the set. This is fundamentally O(n^2).

like image 44
CB Bailey Avatar answered Oct 01 '22 11:10

CB Bailey