简繁EN

LeetCodeNo. 033

[LeetCode with Python] 4. Median of Two Sorted Arrays

Contents

Problem

Problem page: https://leetcode.com/problems/median-of-two-sorted-arrays/
Topics: Divide and Conquer, Array, Binary Search
Difficulty: Hard

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).


Analysis

Find the median of two sorted arrays. I've found quite a few gotchas on LeetCode. For example, "sorted" in this problem means sorted in ascending order. Unlike with other problems that often have a catch, we don't have to suspect a trick and first check whether A and B are sorted in ascending or descending order, or even whether A is ascending while B is descending.

"Median" here is just the usual median: take the m+n numbers in A and B together, sort them in ascending order, and take the one in the middle. If m+n is even, there are two numbers in the middle, so take their average.

The problem asks for O(log(m+n)) time complexity, so we can't count forward one number at a time from the start of the two arrays like we would in a merge. That would take about (m+n)/2 steps, which is O(m+n). My approach is to turn finding the median into finding the k-th smallest number in A and B (counting k from 1). That's findKth(A, B, k) in the code. Let total be m+n, with integer division for total/2. The median is the (total/2+1)-th smallest number, except when total is even. In that case we average it with the (total/2)-th smallest number, so we call findKth twice.

The idea behind findKth is to discard a group of numbers that can't be the answer on each pass and subtract the number discarded from k. If one array has nothing left, the k-th smallest number is the k-th number left in the other array. If k reaches 1, the answer is the smaller of the first numbers left in the two arrays. start_a and start_b keep track of where the remaining parts of A and B start.

  1. On each pass, set half = k/2 and look at the number in position half in the remaining part of A. Call its index index_a and the corresponding index in B index_b. If an array has fewer than half numbers left, look at its last remaining number.
  2. Then compare A[index_a] and B[index_b]. If A[index_a] <= B[index_b], all the remaining numbers in A up through index_a come before the k-th smallest number. Discard that whole range, move start_a to index_a+1, and reduce k by the size of the range. Otherwise, discard the corresponding range in B.

Take the case where A[index_a] <= B[index_b]. Say x is the count of remaining numbers in A through index_a and y is the corresponding count in B through index_b. Both x and y are at most half, so x+y is at most k. Only the x-1 numbers before A[index_a] in A and the y-1 numbers before B[index_b] in B can come before A[index_a]. So the position of A[index_a] is at most x+y-1, which is no later than position k-1. None of those x remaining numbers in A through index_a can be the k-th smallest, so discarding them doesn't change the answer.

Each pass either discards half numbers, roughly halving k, or empties one array, in which case we return on the next pass. The largest k can be is total/2+1, so the loop takes at most O(log(m+n)) passes. The comparisons and index calculations on each pass take O(1) time. Even with two calls, the running time is still O(log(m+n)) and we use only O(1) extra space. To discard a range, just move the indices start_a and start_b. Don't use a slice like A[index_a+1:]. Python copies the slice into a new list, and the copy itself takes linear time.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution:

# @param A, a sorted list
# @param B, a sorted list
# @param k, an integer, 1 <= k <= len(A) + len(B)
# @return the k-th smallest number of A and B together
def findKth(self, A, B, k):

len_a = len(A)
len_b = len(B)
start_a = 0
start_b = 0
while True:
if start_a >= len_a:
return B[start_b + k - 1]
if start_b >= len_b:
return A[start_a + k - 1]
if 1 == k:
return min(A[start_a], B[start_b])

# If A[index_a] <= B[index_b], A[index_a] is at most the (k-1)-th
# smallest of the numbers left, so A[start_a..index_a] can all be
# skipped; the same holds for B in the other case.
half = k / 2
index_a = min(start_a + half, len_a) - 1
index_b = min(start_b + half, len_b) - 1
if A[index_a] <= B[index_b]:
k -= index_a - start_a + 1
start_a = index_a + 1
else:
k -= index_b - start_b + 1
start_b = index_b + 1

# @return a float
def findMedianSortedArrays(self, A, B):

len_a = len(A)
len_b = len(B)
len_total = len_a + len_b
if 0 == len_total:
return ''
if 0 == len_a and 1 == len_b:
return B[0]
if 1 == len_a and 0 == len_b:
return A[0]
if 1 == len_a and 1 == len_b:
return float(A[0] + B[0]) / 2

median_index = len_total / 2
is_odd = (1 == len_total % 2)

if is_odd:
median_num = self.findKth(A, B, median_index + 1)
else:
median_num = float(self.findKth(A, B, median_index) + self.findKth(A, B, median_index + 1)) / 2

return median_num

Article link: https://xnerv.wang/en/leetcode-median-of-two-sorted-arrays/