Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all differences in an array in O(n)

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?

like image 961
WisaF Avatar asked Dec 10 '11 05:12

WisaF


People also ask

Why is array indexing o1?

This is done in O(1) because it is pretty simple (constant number of math calculations) where the element is located given the index, the beginning of the array and the size of each element.

Can we sort an array in O 1?

It depends on how many items can have the same value. If more items can have the same value, then it is not possible to have O(1) with ordinary arrays. (which is O(1) because it is an array). So, now array[5] = 22.


1 Answers

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):

a_i - a_j = (a_i - a_(i-1)) + (a_(i-1) - a_(i-2)) + ... + (a_(j+1) - a_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 skip a_i if a_i = a_(i+1).

All possible differences a_i-a_j with i>j are of the form s_i + s_(i+1) + ... + s_(j+1). So maybe if you count that as having found them, then you did it in O(n) time. To print them, however, may take as many as n(n-1)/2 calls, and that's definitely O(n^2).

like image 186
PengOne Avatar answered Sep 17 '22 12:09

PengOne