0

I have spent hours debugging the following code, but I still cannot figure out where really breaks it. I feel the case ai+bi<=k is causing the error, but I don't know how to fix it. Can someone help?

Here is my code:

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        m, n = len(nums1), len(nums2)
        mid1 = (m+n+1)//2
        mid2 = (m+n+2)//2
        return (self.getKth(nums1, nums2, mid1)+self.getKth(nums1, nums2, mid2))/2

    # k one-indexed
    def getKth(self, a, b, k):
        if not a:
            return b[k-1]
        if not b:
            return a[k-1]
        ai, bi = (len(a)+1)//2, (len(b)+1)//2
        ae, be = a[ai-1], b[bi-1]

        if ai+bi<=k:
            if ae<be:
                return self.getKth(a[ai:], b, k-ai)
            else:
                return self.getKth(a, b[bi:], k-bi)
        else:
            if ae<be:
                return self.getKth(a, b[:bi], k)
            else:
                return self.getKth(a[:ai], b, k)

Question: https://leetcode.com/problems/median-of-two-sorted-arrays/submissions/

Similar Solution(k is zero-based): https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2511/Intuitive-Python-O(log-(m%2Bn))-solution-by-kth-smallest-in-the-two-sorted-arrays-252ms

4
  • 1
    What is the error? Commented Sep 3, 2019 at 3:42
  • When arrays are [1,3] and [2], it keeps iterating when a=[3], b=[2] and k=1. Commented Sep 3, 2019 at 3:46
  • Please provide a (small) example where it breaks. Commented Sep 3, 2019 at 6:09
  • I would try to perform the algorithm by hand for a small example to understand where it breakls (and compare what you do with what the debugger does). Commented Sep 3, 2019 at 6:09

1 Answer 1

1

The bug is in else clause. It should be like this:

        if ae<be:
            return self.getKth(a, b[:bi-1], k)
        else:
            return self.getKth(a[:ai-1], b, k)

You need to use the same indices you use in the following line:

    ae, be = a[ai-1], b[bi-1]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.