Did not manage to google the name of this problem, hope this question will contribute to community.
Consider we have two sorted arrays of numbers, like:
2 8
12 18
45 35
85 48
87 49
97 59
And we want to efficiently take first k
(10) smallest sum combinations of numbers from both arrays. In our case that would be:
2 + 8 = 10
2 + 18 = 20
12 + 8 = 20
12 + 18 = 30
2 + 35 = 37
12 + 35 = 47
2 + 48 = 50
2 + 49 = 51
45 + 8 = 53
12 + 48 = 60
What would be the right approach? I scratched a naive implementation (improved by @sanyash), but it does not get use of the fact that arrays are sorted and the problem feels doable in a linear time...
def smallest_product(k, arr1, arr2):
product_iter = itertools.product(
itertools.islice(arr1, k),
itertools.islice(arr2, k),
)
product_sorted = sorted(product_iter, key=sum)
product_sliced = itertools.islice(product_sorted, k);
return list(product_sliced)
print(smallest_product(10,
[ 2, 12, 45, 85, 87, 98],
[ 8, 18, 35, 48, 49, 59]))
Similar question: efficient sorted Cartesian product of 2 sorted array of integers (but it deals with creating a full resulting array, whereas in my case I need just the first few values)
P.S. I added the python
tag as it's a math problem, but I'll be happy with solution in any language or just an explanation, or a link to wikipedia...