I have this question:
Given two sorted lists (stored in arrays) of size n, find an O(log n) algorithm that computes the nth largest element in the union of the two lists.
I can see there is probably a trick here as it requires the nth largest element and the arrays are also of size n, but I can't figure out what it is. I was thinking that I could adapt counting sort, would that work?
Today in a interview, I was told to write a program which will output the nth highest number in the unsorted array, I solved this using javascript, the program is as follows, var fn50 = function(){ var reverseSort = function(myArray,highest){ var x = 0, y = 0, z = 0, temp = 0, totalNum = myArray.
Suppose we have an unsorted array, we have to find the kth largest element from that array. So if the array is [3,2,1,5,6,4] and k = 2, then the result will be 5. We will sort the element, if the k is 1, then return last element, otherwise return array[n – k], where n is the size of the array.
To find the kth largest element, we can pass k= length(Array) – k. Now let's implement the partition method, which picks the rightmost element as a pivot, puts it at the appropriate index, and partitions the array in such a way that elements at lower indexes should be less than the pivot element.
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
Compare A[n/2] and B[n/2]. If equal, any of them is our result. Other stopping condition for this algorithm is when both arrays are of size 1 (either initially or after several recursion steps). In this case we just choose the largest of A[n/2] and B[n/2].
If A[n/2] < B[n/2], repeat this procedure recursively for second half of A[] and first half of B[].
If A[n/2] > B[n/2], repeat this procedure recursively for second half of B[] and first half of A[].
Since on each step the problem size is (in worst case) halved, we'll get O(log n) algorithm.
Always dividing array size by two to get the index works properly only if n
is a power of two. More correct way of choosing indexes (for arbitrary n
) would be using the same strategy for one array but choosing complementing index: j=n-i
for other one.
Evgeny Kluev gives a better answer - mine was O(n log n) since i didn't think about them as being sorted.
what i can add is give you a link to a very nice video explaining binary search, courtesy of MIT:
https://www.youtube.com/watch?v=UNHQ7CRsEtU
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With