Search code examples
algorithmlanguage-agnostic

Finding the minimum and maximm element from one of many arrays


I received a question during an Amazon interview and would like assistance with solving it.

Given N arrays of size K each, each of these K elements in the N arrays are sorted, and each of these N*K elements are unique. Choose a single element from each of the N arrays, from the chosen subset of N elements. Subtract the minimum and maximum element. This difference should be the least possible minimum.

Sample:

N=3, K=3

N=1 : 6, 16, 67
N=2 : 11,17,68
N=3 : 10, 15, 100

here if 16, 17, 15 are chosen, we get the minimum difference as 17-15=2.


Solution

  • I can think of O(N*K*N)(edited after correctly pointed out by zivo, not a good solution now :( ) solution.
    1. Take N pointer initially pointing to initial element each of N arrays.

    6, 16, 67
    ^ 
    11,17,68
    ^
    10, 15, 100
    ^ 
    

    2. Find out the highest and lowest element among the current pointer O(k) (6 and 11) and find the difference between them.(5)
    3. Increment the pointer which is pointing to lowest element by 1 in that array.

     6, 16, 67
        ^ 
     11,17,68
     ^
     10, 15, 100 (difference:5)
     ^ 
    

    4. Keep repeating step 2 and 3 and store the minimum difference.

     6, 16, 67
        ^ 
     11,17,68
     ^
     10,15,100 (difference:5)
        ^ 
    
    
     6, 16, 67
        ^ 
     11,17,68
        ^
     10,15,100 (difference:2)
        ^ 
    

    Above will be the required solution.

     6, 16, 67
        ^ 
     11,17,68
        ^
     10,15,100 (difference:84)
           ^ 
    
     6, 16, 67
            ^ 
     11,17,68
        ^
     10,15,100 (difference:83)
           ^ 
    

    And so on......

    EDIT:

    Its complexity can be reduced by using a heap (as suggested by Uri). I thought of it but faced a problem: Each time an element is extracted from heap, its array number has to be found out in order to increment the corresponding pointer for that array. An efficient way to find array number can definitely reduce the complexity to O(K*N log(K*N)). One naive way is to use a data structure like this

    Struct
    {
        int element;
        int arraynumer;
    }
    

    and reconstruct the initial data like

     6|0,16|0,67|0
    
     11|1,17|1,68|1
    
     10|2,15|2,100|2
    

    Initially keep the current max for first column and insert the pointed elements in heap. Now each time an element is extracted, its array number can be found out, pointer in that array is incremented , the newly pointed element can be compared to current max and max pointer can be adjusted accordingly.