in reply to Challenge: Sorting Sums Of Sorted Series

Hi Monks

The following algorithm seems to need 4+N+M memory ... and therefore fulfills the challenge :-)

  1. val = N1 + M1
  2. loop
    1. for all i, j: if (Ni+Mj == val) print (Ni+Mj)
    2. nextval = val
    3. for all i, j: if ((Ni+Mj)>val) && ((Ni+Mj) < nextval) => nextval = (Ni + Mj)
    4. if (val == nextval) => exit # we are finished
    5. val = nextval
  3. goto 2.

So in additon to N and M, you need the constant space for 4 variables (i, j, val, nextval) and for the temporary sums. :-)
However the runtime would be O(N^2*M^2) (*) - so I wouldn't consider it efficient ;-)

Rata

(*) 2 * N * M for the inner loop - and a maximum N * M for the outer one

note: the restriction that N and M are sorted can easily be dropped with the algorithm above (just replace line 1 with lines 2.2.-2.5)

update: Limbic~Region just told me that blokhead posted nearly the same solution before (he needs one variable more, which doesn't affect the complexity O((NM)^2). ... I didn't want to waste bandwidth, but I fear duplicated solutions are the risk if one is not cheating ;-)

  • Comment on Re: Challenge: Sorting Sums Of Sorted Series