Given three sorted arrays of variable length, efficiently compute the minimum range with at least one element from each array.

For example,

Input: 3 sorted arrays of variable length
 
[ 3, 6, 8, 10, 15 ]
[ 1, 5, 12 ]
[ 4, 8, 15, 16 ]
 
Output: Minimum range is 3–5
 
 
Input: 3 sorted arrays of variable length
 
[ 2, 3, 4, 8, 10, 15 ]
[ 1, 5, 12 ]
[ 7, 8, 15, 16 ]
 
Output: Minimum range is 4–7

Practice this problem

A naive solution is to compute the range of every possible triplet and return the minimum of all values. The time complexity of this solution is O(n3) for an input containing n elements, as we need three nested loops to consider every triplet. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The minimum range is [3, 5]

Java


Download  Run Code

Output:

The minimum range is [3, 5]

Python


Download  Run Code

Output:

The minimum range is (3, 5)

 
We can quickly reduce the time complexity to linear as we don’t need to consider every triplet. The idea is to take advantage of the fact that the arrays are already sorted. In the following solution in C++, Java, and Python, we compute the range for some selected triplets and return the minimum.

C++


Download  Run Code

Output:

The minimum range is [4, 7]

Java


Download  Run Code

Output:

The minimum range is [4, 7]

Python


Download  Run Code

Output:

The minimum range is (4, 7)

The time complexity of the above solution is O(n), where n is the total number of elements in all three arrays.