Question: Given a sorted array A find all possible difference of elements from A.
My solution:
for (int i=0; i<n-1; ++i) {
for (int j=i+1; j<n; ++j) {
System.out.println(Math.abs(ai-aj));
}
}
Sure, it’s O(n^2), but I don’t over count things at all. I looked online and I found this: http://www.careercup.com/question?id=9111881. It says you can’t do better, but at an interview I was told you can do O(n). Which is right?
A first thought is that you aren’t using the fact that the array is sorted. Let’s assume it’s in increasing order (decreasing can be handled analogously).
We can also use the fact that the differences telescope (i>j):
Now build a new sequence, call it s, that has the simple difference, meaning
(a_i - a_(i-1)). This takes only one pass (O(n)) to do, and you may as well skip over repeats, meaning skipa_iifa_i = a_(i+1).All possible differences
a_i-a_jwithi>jare of the forms_i + s_(i+1) + ... + s_(j+1). So maybe if you count that as having found them, then you did it inO(n)time. To print them, however, may take as many asn(n-1)/2calls, and that’s definitelyO(n^2).