Question

3. (20 pts.) You are given two sorted lists of numbers with size m and n. Give an O(logn+ logm) time algorithm for computing

0 0
Add a comment Improve this question Transcribed image text
Answer #1

3.

This problem can be easily solved using Divide and Conquer approach.
We compare the median of arrays arr1 and arr2, let us call these indices mid1 and mid2 respectively.

Let us assume arr1[mid1] is more than k, this means that the elements after  mid2 cannot be the required element. We then set the last element of arr2 to be arr2[mid2].

In this way, we define a new subproblem with half the size of one of the arrays.

PSEUDOCODE

int kth(int arr1[], int arr2[], int m, int n, int k, int st1, int st2)

{

if (st1 == m)

{

return arr2[st2 + k - 1];

}

if (st2 == n)

{

return arr1[st1 + k - 1];

}

if (k == 0 || k > (m - st1) + (n - st2))

{

return -1;

}

if (k == 1)

{

return (arr1[st1] < arr2[st2]) ? arr1[st1] : arr2[st2];

}

int curr = k / 2;

if (curr - 1 >= m - st1)

{

if (arr1[m - 1] < arr2[st2 + curr - 1])

{

return arr2[st2 + (k - (m - st1) - 1)];

}

else

{

return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr);

}

}

if (curr - 1 >= n - st2)

{

if (arr2[n - 1] < arr1[st1 + curr - 1])

{

return arr1[st1 + (k - (n - st2) - 1)];

}

else

{

return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2);

}

}

else

if (arr1[curr + st1 - 1] < arr2[curr + st2 - 1])

{

return kth(arr1, arr2, m, n, k - curr, st1 + curr, st2);

}

else

{

return kth(arr1, arr2, m, n, k - curr, st1, st2 + curr);

}

}

NOTE: As per HOMEWORKLIB POLICY, I am allowed to answer specific number of questions (including sub-parts) on a single post. Kindly post the remaining questions separately and I will try to answer them. Sorry for the inconvenience caused.

Add a comment
Know the answer?
Add Answer to:
3. (20 pts.) You are given two sorted lists of numbers with size m and n....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (25pts) You are given two sorted lists of size m and n. Give an O(log m...

    (25pts) You are given two sorted lists of size m and n. Give an O(log m log n) time algorithm for computing the k-th smallest element in the union of the two lists Note that the only way you can access these values is through queries to the databases. Ina single query, you can specify a value k to one of the two databases, and the chosen database will return the k-th smallest value that it contains. Since queries are...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT