Monday 3 October 2016

Given 4 lists of numbers (including -ve no.s) of length n, find all combinations of numbers (a, b, c, d) from respective lists which sum to zero.

We need to find 4 numbers, one from each list which sum up to zero.

Solving for 2 lists:
We can solve for 2 lists in O(n) as follows,

  • Put the first list in a hashmap.
  • Iterate the second list
    • for each element s(i) in second list, lookup "0-s(i)" in the map
    • If found we got one pair

Solving for 4 lists:
  • Combine first and second list as follows,
    • For each combination of f(i) and s(j), create an element f(i)+s(j)
    • This gives us n^2 elements
  • Combine 3rd and 4th lists in a similar manner and get another n^2 list.
  • Now we can solve for these two lists of size n^2 in O(n^2).

No comments:

Post a Comment