I recently encountered this question in an interview. I wasn't really able to come up with an answer to this. I started with, take first element from first array, and then find how many elements are greater than this element in the other array. But then, I mean, I don't know, couldn't really form a solution. The problem is as follows:
Given two sorted arrays A and B, generate all possible arrays such that first element is taken from A then from B then from A and so on in increasing order till the arrays exhausted. The generated arrays should end with an element from B.
Eg:
A = {10, 15, 25}
B = {1, 5, 20, 30}
The resulting arrays are:
10 20
10 20 25 30
10 30
15 20
15 20 25 30
15 30
25 30
I am not looking for a code, just an algo/pseduo-code would do fine. Thanks!
Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.
The idea is to sort the A1[] array and then according to A2[] store the elements. Let the size of A1[] be m and the size of A2[] be n. Create a temporary array temp of size m and copy the contents of A1[] to it. Create another array visited[] and initialize all entries in it as false.
A simple solution is to first find intersection of two arrays and store the intersection in a temporary array, then find the intersection of third array and temporary array. Time complexity of this solution is O(n1 + n2 + n3) where n1, n2 and n3 are sizes of ar1[], ar2[] and ar3[] respectively.
How about using a directed graph with a BFS search of paths.
Update
Per suggestion by @MiljenMikic, you can exploit the fact that the arrays are sorted by speeding up Step 1. You don't have to search all elements in the other array to find greater-than elements. Just keep track of the last found and move the pointer forward as you search.
BFS solution that @dpmcmlxxvi proposed is interesting. In addition, I would suggest a recursive variant. Some basic points:
arrays are sorted - use that information! When you see sorted arrays, always think of binary search - in this case you should recursively pass last added element and then, in the other array, binary search for the first element that is greater than that last element
if the last added element was from B, add the current working array to the resulting list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With