What is the efficient solution for computing the sum of all pair sum square in an array?

Viewed 49

Given an Array we need to compute . What is the running time of a time-efficient solution?

I thought the running time of the time-efficient solution for the equation

would be n^2 (quadratic time) but the solution is n (linear time).

Can someone explain me how is it n (linear time)?

1 Answers

Just you need to rewrite the formula. The inner formula is . Hence, you can take out from the inner sum:

Now just we need to compute , , and . As each of them can be done in O(n), we can find the final result in O(n).

Notice that, you can do it in O(n^2) by two nested loops (as you said). But it is not optimized. You can find similar techniques in matrix multiplication (Strassen algorihtm) as well.

Related