From 4 given arrays(not sorted), find the elements from each array whose sum is equal to some number X

Viewed 873

Suppose there are 4 unsorted arrays as given below:

A = [0, 100, -100, 50, 200]
B = [30, 100, 20, 0]
C = [0, 20, -1, 80]
D = [50, 0, -200, 1]

Suppose X is 0, so the few of the possible O/P should be (pick 1 element from each array which satisfy condition):

0,0,0,0
-100, 100, 0, 0
-100, 30, 20,50 .. etc.

I was able to devise the algorithm which can do this in O(n^3LogN), is there any better way to achieve the same?

My Solution:

1- Sort each array.

2- Fixed the element from array A.

3- run three loops for the rest of the arrays and take the sum of each element:

if sum > 0 (return -1, no such elements exit)

if sum == 0 (return current elements)

if sum < 0 (then advance the pointer from the array for which the current element is minimum.)

Any suggestion over this?

5 Answers

Assuming your arrays all have the same length n (+/- some constant value) you can get O(n^3) by using a set for the fourth array:

from itertools import product

ds = set(D)
for a, b, c in product(A, B, C):
    d = X - a - b - c
    if d in ds:
        print(a, b, c, d)

If one or multiple arrays contain (many) extreme values you can also take shortcuts by checking the running sum against the min and max of subsequent arrays to see if X can still be reached. For example:

ds = set(D)
c_min, c_max = min(C), max(C)
d_min, d_max = min(ds), max(ds)
for a in A:
    for b in B:
        s = a + b
        if s + c_min + d_min > X or s + c_max + d_max < X:
            continue  # Shortcut here.
        for c in C:
            d = X - a - b - c
            if d in ds:
                print(a, b, c, d)

You can further extend this by storing solutions that have already been found for a running sum (of the first two arrays for example) and hence taking a shortcut whenever such a sum is encountered again (by reordering with the min/max check one can avoid repeated computation of s + min/max values):

ds = set(D)
c_min, c_max = min(C), max(C)
d_min, d_max = min(ds), max(ds)
shortcuts = {}
for a in A:
    for b in B:
        s = a + b
        if s in shortcuts:
            for c, d in shortcuts[s]:
                print(a, b, c, d)
            continue
        shortcuts[s] = []
        if s + c_min + d_min > X or s + c_max + d_max < X:
            continue
        for c in C:
            d = X - a - b - c
            if d in ds:
                print(a, b, c, d)
                shortcuts[s].append((c, d))

We can have O(n^2) by hashing pair sums for A and B and checking if for any one of them, sum_AB[i] there might be an X - sum_AB[i] hashed in the pair sums of C and D.

In some circumstances it could be more efficient to enumerate those sums by multiplying each pair of lists as counts of coefficients in polynomials, using a FFT for O(m log m) complexity, where m is the range.

a kind of dynamic programming approach.

initialize sums (a dict of the form {possible_sum0: [way_to_get_sum0, ...]}) with the first list A. this results in

sums = {0: [[0]], 100: [[100]], -100: [[-100]], 50: [[50]], 200: [[200]]}

the update that dictionary with the lists B and C. sums will now contain entries like

sums = {..., 
        30: [[0, 30, 0]], 
        50: [[0, 30, 20], [50, 0, 0]], 
        29: [[0, 30, -1]], ...}

then in find_sum i sort the last list D and the sums for some speedup and break if a give sum X is no longer accessible.

here is the code:

from collections import defaultdict

A = [0, 100, -100, 50, 200]
B = [30, 100, 20, 0]
C = [0, 20, -1, 80]
D = [50, 0, -200, 1]

def initialize_sums(lst):
    return {item: [[item]] for item in lst}

def update_sums(sums, lst):
    new_sums = defaultdict(list)
    for sm, ways in sums.items():
        for item in lst:
            new_sum = sm + item
            for way in ways:
                new_sums[new_sum].append(way + [item])
    return new_sums

def find_sum(sums, last_lst, X):
    last_lst = sorted(last_lst)
    ret = []
    for sm, ways in sorted(sums.items()):
        for item in last_lst:
            x = sm + item
            if x > X:
                break
            if x == X:
                for way in ways:
                    ret.append(way + [item])
                break
    return ret


sums = initialize_sums(lst=A)
sums = update_sums(sums, lst=B)
sums = update_sums(sums, lst=C)

ret = find_sum(sums, last_lst=D, X=0)
print(ret)
# [[-100, 30, 20, 50], [0, 0, -1, 1], [-100, 100, -1, 1], ...]

...did not analyze the overall complexity though.

find all combinations for an array

def dOfSums(li):
  return {sum(x):x for x in sum([list(itertools.combinations(li, i)) for i in range(2,len(li))],[])}

find sums for a number in an array

def findSums(li, num):
    return [((namestr(l), dOfSums(l)[num]) for l in li if num in dOfSums(l).keys() ]

name the array

def namestr(obj):
    return [name for name in globals() if globals()[name] is obj].pop()

test

for el in findSums([A,B,C,D],50):
    print(el)

('A', (0, 100, -100, 50))
('B', (30, 20, 0))
('D', (50, 0))

for el in findSums([A,B,C,D],100):
    print(el)

('A', (0, -100, 200))
('B', (100, 0))
('C', (0, 20, 80))

for el in findSums([A,B,C,D],0):
    print(el)

('A', (0, 100, -100))
A = [0, 100, -100, 50, 200]
B = [30, 100, 20, 0]
C = [0, 20, -1, 80]
D = [50, 0, -200, 1]

solutions = [(x1,x2,x3,x4) for x1 in A for x2 in B for x3 in C for x4 in D if sum([x1,x2,x3,x4]) == 0]
print(solutions)

Output:

>>>[(0, 0, 0, 0), (0, 0, -1, 1), (100, 100, 0, -200), (100, 20, 80, -200), (-100, 30, 20, 50), (-100, 100, 0, 0), (-100, 100, -1, 1), (-100, 20, 80, 0), (200, 0, 0, -200)]

This does exactly what you listed in your steps and works for any size, I don't know if it can get any easier finding all solutions for different list sizes.

Related