Topics

Given an array a of length n, find the sum of all pairwise products a[i] Γ— a[j] for all pairs of indices (i, j) such that i < j. In other words, we need to calculate:

Define:

Now, consider the square of this sum:

Expanding gives:

Rearrange this equation to solve for the sum of all pairwise products:

Divide both sides by 2:

Intuition Behind the Formula

  • : This is the square of the sum of all elements. It naturally includes every possible product , but it also includes the squares which we don’t need
  • Subtracting : This removes the self-products (i.e., when i = j)
  • Division by 2: Since every pair (i, j) appears twice in (once as and once as ), dividing by 2 gives the correct total