Payments app~40 min2s · 256 MBtarget O(log(min(m, n))) time, O(1) spaceclassic twin: lc-4binary-search
A payments platform stores the settlement amounts of two regions in two files. Each file is sorted from the smallest amount to the largest. The finance team wants the median amount of all the settlements together, without merging the files.
When the total count is even, the median is the average of the two middle amounts, which may end in .5. To keep every answer a whole number, you return twice the median.
Write twice_the_median(first, second).
first and second are sorted from the smallest to the largest. Either may be empty, but not both.t amounts.t is odd, return twice the middle amount. When t is even, return the sum of the two middle amounts.Input: first = [1, 4, 9], second = [2, 3, 7, 8]
Output: 8The merged list is 1, 2, 3, 4, 7, 8, 9, so the median is 4, and twice the median is 8. The solution never builds it. It searches for the cut i in the shorter list. The cut j = 4 - i in the other list then makes the left parts hold the 4 smallest amounts together.
| lo | hi | i | j | first[i] |
second[j-1] |
first[i] at least second[j-1]? |
Decision |
|---|---|---|---|---|---|---|---|
| 0 | 3 | 1 | 3 | 4 | 7 | no | the cut in first is too far left: lo becomes 2 |
| 2 | 3 | 2 | 2 | 9 | 3 | yes | hi becomes 2 |
The cut is i = 2, j = 2. The left parts are 1, 4 from first and 2, 3 from second. The largest of them is 4. The total is odd, so the answer is 2 × 4 = 8.
Input: first = [1, 2], second = [3, 4]
Output: 5The merged list is 1, 2, 3, 4. The middle amounts are 2 and 3, and their sum is 5.
Input: first = [], second = [6]
Output: 12The only amount is 6, so twice the median is 12.
0 ≤ first.length, second.length ≤ 300,000, and at least one amount in total0 ≤ amount ≤ 1,000,000,000Merging both lists reads up to 600,000 amounts. That is fast, but the point of the task is to read about 20 of them. The first attempt below removes the smallest amount one at a time, which costs about t × t / 2 steps, far over the budget when t is large.