I saw this question in a programming interview blog.
If pairwise sums of
nnumbers are given in non-decreasing order identify the individual numbers. If the sum is corrupted print-1.
Example:
i/p: 4 5 7 10 12 13
o/p: 1 3 4 9
A hint would suffice.
Let
Bbe the list of pairwise sums, withB[0] <= B[1] <= ... <= B[m-1]and letAbe the original list of numbers that we’re trying to find, withA[0] < A[1] < ... < A[n-1], wherem = n(n-1)/2.Given
A[0], computeAin polynomial timeBuild
Aup from smallest element to largest. Suppose that we already knowA[0]. Then, sinceB[0]is the smallest element inB, it can only arise asA[0] + A[1]. Similarly,B[1]must equalA[0] + A[2]. Therefore, if we knowA[0], we can computeA[1]andA[2].After that, however, this pattern breaks down.
B[2]could either beA[0] + A[3]orA[1] + A[2]and without prior knowledge, we cannot know which one it is. However, if we knowA[0], we can computeA[1]andA[2]as described above, and then removeA[1] + A[2]fromB. The next smallest element is then guaranteed to beA[0] + A[3], which allows us to findA[3]. Continuing like this, we can find all ofAwithout ever backtracking. The algorithm looks something like this:Here’s how this works from your example where
B = [4,5,7,10,12,13]if we knowA[0]=1:So it all comes down to knowing
A[0], from which we can compute the rest ofA.Compute
A[0]in polynomial timeWe can now simply try every possibility for
A[0]. Since we knowB[0] = A[0] + A[1], we knowA[0]must be an integer between0andB[0]/2 - 1. We also know thatMoreover, there is some index
iwith2 <= i <= n-1such thatWhy? Because the only entries potentially smaller than
A[1]+A[2]are of the formA[0] + A[j], and there are at mostn-1such expressions. Therefore we also know thatfor some
2 <= i <= n-1. This, together with the fact thatA[0]lies between0andB[0]/2-1gives only a few possibilities forA[0]to test.For the example, there are two possibilities for
A[0]:0or1. If we try the algorithm withA[0]=0, here’s what happens: