← Whiteboard questions

Median of Two Sorted Arrays

Find the middle value of two sorted arrays

DSA, Hard, Binary Search

Which structure or algorithm, and what does it cost.

Two lists a and b are each sorted from smallest to largest. One of them may be empty, but not both. Treat all their numbers as one group and return the group's median: the middle number in sorted order, or the average of the two middle numbers when the count is even. Return a decimal number, and do better than merging the lists.

Examples

Input a = [2, 6, 10], b = [4, 5, 12, 14]
Output 6.0
Why Together the numbers sort to 2, 4, 5, 6, 10, 12, 14. There are 7, so the median is the 4th number, 6.
Input a = [1, 3], b = [8, 9]
Output 5.5
Why Sorted together: 1, 3, 8, 9. The middle two are 3 and 8, and their average is 5.5.
Input a = [], b = [4, 10]
Output 7.0
Why Edge case: one list is empty. The median comes from the other list alone.

Constraints

Your answer must contain

Target Aim for O(log(min(m, n))) time and O(1) memory, where m and n are the list lengths.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Suppose you had merged the two lists. Where would the median sit, and what would lie on each side of it?

Hint 2 the approach

Cut one list at some position. That fixes how many numbers the other list must give to the left half.

Hint 3 the key step

Binary search the cut in the shorter list. A cut is right when each list's last left number is at most the other list's first right number.

Walkthrough

Full walkthrough brute force to best

Brute force

Merge both lists into one sorted list and read the middle number or the middle two. That is O(m + n) time and O(m + n) memory. Counting up to the middle with two pointers saves the memory but is still O(m + n) time, which is too slow for lists this long.

Best method

Cut each list in two so that the left parts together hold half of all the numbers, with one extra on the left when the count is odd. Take i numbers from the shorter list a and the rest of the half from b. The cut is right when the last left number of a is at most the first right number of b, and the last left number of b is at most the first right number of a. Then every left number is at most every right number, so the median sits beside the cut. With an odd count it is the larger of the two left numbers. With an even count it is the average of the larger left number and the smaller right number. If the last left number of a is too big, move the cut in a left. Otherwise move it right. Binary search i in the shorter list. A cut at the start or end of a list has no number on one side, so use minus infinity on the left and infinity on the right.

Hand trace

Run on a = [2, 6, 10] and b = [4, 5, 12, 14]. The left half holds 4 numbers. Try i = 1, so 3 come from b. Beside the cut, the left numbers are 2 and 12, and the right numbers are 6 and 14. 12 is larger than 6, so a must give more: the cut moves right. Try i = 2, so 2 come from b. The left numbers are 6 and 5, and the right numbers are 10 and 12. 6 is at most 12 and 5 is at most 10, so the cut is right. The count 7 is odd, so the median is the larger left number, 6.0.

Code

def find_median(a, b):
    if len(a) > len(b):
        a, b = b, a                 # search the shorter list
    m, n = len(a), len(b)
    half = (m + n + 1) // 2         # size of the left half
    lo, hi = 0, m
    while lo <= hi:
        i = (lo + hi) // 2          # numbers taken from a
        j = half - i                # numbers taken from b
        a_left = a[i - 1] if i > 0 else float("-inf")
        a_right = a[i] if i < m else float("inf")
        b_left = b[j - 1] if j > 0 else float("-inf")
        b_right = b[j] if j < n else float("inf")
        if a_left > b_right:
            hi = i - 1
        elif b_left > a_right:
            lo = i + 1
        elif (m + n) % 2:
            return float(max(a_left, b_left))
        else:
            return (max(a_left, b_left) + min(a_right, b_right)) / 2

Time and memory

O(log(min(m, n))) time, because the binary search runs on the shorter list only. O(1) memory.

Common mistakes

  • Searching the longer list. The matching cut in the other list can then fall below zero or past its end. Always search the shorter list.
  • Leaving out the end cases. When a cut is at the start or end of a list, use minus infinity or infinity so the comparisons still work.
  • Using (m + n) // 2 as the left half for both parities. With an odd count the left half needs the extra number, so use (m + n + 1) // 2.
  • Returning an integer. An even count can give a result ending in .5, so return a decimal number.

Related problems

More Binary Search problems
Median of Two Sorted Arrays: walkthrough and Python solution