Binary Search
45 / 170Binary SearchLesson 7 of 8About 90 min
The hardest binary search in the set. The thing being searched for is not a value but a place to cut.
Two sorted arrays, and you need the median of their combined contents in logarithmic time.
Merging them takes O(n + m) and is trivially correct. Say that first. The logarithmic solution exists and is genuinely fiddly, and offering the linear one as a baseline before attempting it is the right order.
Everything else in this unit is a variation on one template. This problem is that template plus a reframe that most people do not find under time pressure.
Give the merge solution, state its cost, then attempt the cut. Getting partway with a clear explanation of what you are searching for is worth more than a memorized version you cannot justify.
Time and space for the cut-based median, searching over the shorter array, with arrays of length n and m. Answer in terms of the smaller of the two.
low, high = 0, len(shorter)while low <= high: take_from_shorter = (low + high) // 2 take_from_longer = half - take_from_shorter # four boundary elements, two comparisons, adjust low or high ...Build the piece the search needs. boundary_values returns the four elements around a cut as (a_left, a_right, b_left, b_right), using infinities where an element does not exist. cut_is_valid reports whether the cut correctly separates the halves. adjust returns "left" if the first array is contributing too much, "right" if too little, and "done" when the cut is valid.
Tests
a, b = [1, 3, 8], [7, 9, 10, 11]print(boundary_values(a, b, 1, 3))print(boundary_values(a, b, 0, 3))print(cut_is_valid(a, b, 2, 3), cut_is_valid(a, b, 3, 3))print(adjust(a, b, 3, 3), adjust(a, b, 2, 3), adjust(a, b, 0, 3))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.