Techie Delight
Coding made easy
Given three sorted arrays of variable length, efficiently compute the minimum range with at-least one element from each of the arrays.

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

Naive solution is to compute the range for every possible triplet and return minimum of all values. The time complexity of this solution is O(n3) as we need three nested loops to consider every triplet.

C++

Download   Run Code

Output:

Minimum Range is [3, 5]

Java

Download   Run Code

Output:

Minimum Range is [3, 5]

Python

Download   Run Code

Output:

Minimum Range is (3, 5)

Download   Run Code
Output:

Minimum Range is [3, 5]

Download   Run Code
Output:

Minimum Range is [3, 5]

Download   Run Code
Output:

Minimum Range is (3, 5)

We can easily 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 solution below, we compute the range for some selected triplets and return the minimum.
The algorithm can be implemented as follows in C++, Java and Python:

C++

Download   Run Code

Output:

Minimum Range is [4, 7]

Java

Download   Run Code

Output:

Minimum Range is [4, 7]

Python

Download   Run Code

Output:

Minimum Range is (4, 7)

Download   Run Code
Output:

Minimum Range is [4, 7]

Download   Run Code
Output:

Minimum Range is [4, 7]

Download   Run Code
Output:

Minimum Range is (4, 7)

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