There are many sorted arrays. Find a minimum range, so that in each array there's at least one integer within this range.
Solution:
Do a "merge" operation (kind of) by maintaining a priority queue of minimum elements from each array. The range of the whole queue is the range of the current interval. Iterate over all elements until one of the arrays is exhausted and choose the minimum range. The priority queue guarantees that there's at least one element from each array present. The fact that the queue is sorted allows as to quickly retrieve the current min and max elements and therefore determine the current range. It's best to maintain the heap using a BST - all operations (including getMax/Min) will take O(log M), where M is the number of input arrays.
Example:
input {0,10,255} {2 , 11 , 257} {4,12,258} Let's take the first element from each array and push them into priority queue. step 0: queue: [0,2,4] range:0-4 step 1: pop 0 from queue , push next element to 0 from first array queue: [2,4,10] range: 2-10 step2: pop 2 , push 11 queue: [4,10,11] range: 4-11 step3: pop 4 , push 12 queue: [10,11,12] range: 10-12 <----- minimal range etc...
Complexity:
time - O(n log n) (we iterate once and maintain a heap)Links and credits:
space - O(M), where M - the number of arrays
http://www.careercup.com/question?id=5103437989543936