4

Here is a problem:

Suppose we have following arrays:

[1,2,9]
[3,6,7]
[4,11]
[8,10,12]

Items in array are unique and ordered. The task is to find the shortest sequence length which will contain at least one element of every array, but these elements should go one by one (without gaps, can't be [1,3]) and also ordered. So in this case the answer is:

5 => [7,8,9,10,11]

Is there efficient way to do this?

Oleksii Duzhyi
  • 1,203
  • 3
  • 12
  • 26

2 Answers2

2

You may use two pointers algorithm (Sorry to say that I didn't find any reference).The complexity is O(nlogn), n is the sum of elements in all arrays.

First, putting all the elements in an 1d-array, donating each with array index. Just like this,

struct A{
    int value;
    int array_id;
};

Then, sort the elements by value(O(nlogn)). Our problem changes to find shortest continuous sequence that covers all arrays. This can be done by two pointers algorithm. The complexity is O(n).

So total complexity is O(nlogn).

throwit
  • 714
  • 3
  • 13
2

This can be solved easily as below.

  1. List item
  2. initialize smallest_range as MAX_INT
  3. keep 3 pointers/index p1, p2 and p3 which points to the first elements of lists L1, L2 and L3 respectively.
  4. find the max value and min value pointed/indexed by p1, p2 and p3
  5. difference of max value and min value discovered in step 3 is the current range. compare it with smallest_range and update it, if found smaller.
  6. increment the pointer/index of min value found in step 3.
  7. repeat step 3 to 5 until the pointer/index of min value is in range.

Alse check this discussion. It is about your problem. There you can find c++ and java codes too

Gor
  • 2,808
  • 6
  • 25
  • 46
  • The only thing I'd like to mention is to use minimum binary heap and not be certain about exact number of arrays, lets say there are n arrays – Oleksii Duzhyi Oct 23 '15 at 12:22