''' I assume you have already known that: the quantities of elements before and after the medium number is equal, which are both equal to (m+n)/2. And the numbers before the medium number must be the prefix of both arraies. However, there are some exceptions: one of the two arraies may don't contain any number, the prefix of one array may is equal to the array itself. So you must pay your whole attention on boundary conditions to assure that your program won't access an invalid position like nums1[-1] or nums[n]. You can just avoid this by inserting -1MAXN at the beginning and MAXN at the end, where MAXN means a large enough number that bigger than the max number in the previous array. In this case you can use -100000 and 100000. since you are supposed to find the medium number, inserting a smallest and a biggest number doesn't matter. And then you can ignore the condition that array is empty, cause there must be at least two numbers. What's more, you can insert an extra inf at the end or an extra -inf at the beginning. Then you won't consider accessing an invalid position. Here is my code. I know is ugly to read, but is easy to write. :) #散装塑料英文 ''' classSolution: deffindMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: len1, len2 = len(nums1)+2, len(nums2)+2 tlen = int( (len1+len2) / 2 ) # need's length lt, rt = 1, len1 nums1.append(1000001) nums1.append(1000001) nums2.append(1000001) nums2.append(1000001) nums1.insert(0,-1000001) nums1.insert(0,-1000001) nums2.insert(0,-1000001) nums2.insert(0,-1000001) while(lt < rt): mid = int ( (lt + rt + 1 ) / 2 ) t = tlen - mid if(t > len2): lt = mid continue if(t < 0): rt = mid -1 continue if( nums2[t+1] < nums1[mid] ): rt = mid - 1 else: lt = mid if( (len1+len2) %2 != 0): returnmin( nums1[lt+1] , nums2[tlen-lt+1] ) else: summ = max ( nums1[lt], nums2[tlen-lt] ) summ += min ( nums1[lt+1] , nums2[tlen-lt+1]) return summ / 2