I have 2 sorted arrays of integers, how to find the kth largest element in O (logn)?

I was asked this question in an interview. I was able to do this O (n) times, obviously, but I can't think of a solution method in O (logn). It sounds like using some separation and rest algorithms, but I'm not sure.

+4
source share
1 answer

Trim both sizes k. If necessary, ask the program to imagine infinity at the end of one or both arrays to bring them to size k; this will not affect the asymptotic runtime. (In a real implementation, we are likely to do something more efficient.)

k/2'- . , k- ; k/2'th A, - B. A B, k/2- , . , k = 1.

A , B . K/2- , , , A, k- .

, Python:

def kth(array1, array2, k):
    # Basic proof of concept. This doesn't handle a bunch of edge cases
    # that a real implementation should handle.
    # Limitations:
    #   Requires numpy arrays for efficient slicing.
    #   Requires k to be a power of 2
    #   Requires array1 and array2 to be of length exactly k
    if k == 1:
        return min(array1[0], array2[0])
    mid = k//2 - 1
    if array1[mid] > array2[mid]:
        array1, array2 = array2, array1
    return kth(array1[k//2:], array2[:k//2], k//2)

, .

+7

All Articles