Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I hope I am not answering your homework as it has been over a year since this question was asked. Here is a tail recursive solution that will take log(len(a)+len(b)) time.</p> <p>Assumption: The inputs are right. i.e. k is in the range [0, len(a)+len(b)]</p> <p>Base cases:</p> <ul> <li>If length of one of the arrays is 0, the answer is kth element of the second array.</li> </ul> <p>Reduction steps:</p> <ul> <li>If mid index of <code>a</code> + mid index of <code>b</code> is less than <code>k</code> <ul> <li>If mid element of <code>a</code> is greater than mid element of <code>b</code>, we can ignore the first half of <code>b</code>, adjust <code>k</code>.</li> <li>else ignore the first half of <code>a</code>, adjust <code>k</code>.</li> </ul></li> <li>Else if <code>k</code> is less than sum of mid indices of <code>a</code> and <code>b</code>: <ul> <li>If mid element of <code>a</code> is greater than mid element of <code>b</code>, we can safely ignore second half of <code>a</code></li> <li>else we can ignore second half of <code>b</code></li> </ul></li> </ul> <p>Code:</p> <pre class="lang-python prettyprint-override"><code>def kthlargest(arr1, arr2, k): if len(arr1) == 0: return arr2[k] elif len(arr2) == 0: return arr1[k] mida1 = len(arr1)/2 mida2 = len(arr2)/2 if mida1+mida2&lt;k: if arr1[mida1]&gt;arr2[mida2]: return kthlargest(arr1, arr2[mida2+1:], k-mida2-1) else: return kthlargest(arr1[mida1+1:], arr2, k-mida1-1) else: if arr1[mida1]&gt;arr2[mida2]: return kthlargest(arr1[:mida1], arr2, k) else: return kthlargest(arr1, arr2[:mida2], k) </code></pre> <p>Please note that my solution is creating new copies of smaller arrays in every call, this can be easily eliminated by only passing start and end indices on the original arrays.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload