Ad platform~15 min2s · 256 MBtarget O(n + m) time, O(n + m) spacemerge-sorted · two-pointers · sorting
An ads app prices its ad slots in two lists. The morning list is printed with the cheapest slot first. The evening list was printed the other way round, with the dearest slot first.
Your team lead needs one list of all the prices, cheapest first, with every price kept even when it appears twice.
Write merge_price_rows(morning, evening).
morning is sorted from the smallest price to the largest. evening is sorted from the largest price to the smallest. Either list can be empty.Input: morning = [2, 5, 5, 9], evening = [8, 6, 5, 1]
Output: [1, 2, 5, 5, 5, 6, 8, 9]The cheapest price of the morning list is at its start. The cheapest price of the evening list is at its end. Keep a pointer at each, compare the two, take the smaller and move that pointer.
| Step | Morning pointer | Evening pointer | Taken | Merged so far |
|---|---|---|---|---|
| 1 | 2 | 1 | 1 (evening) | 1 |
| 2 | 2 | 5 | 2 (morning) | 1, 2 |
| 3 | 5 | 5 | 5 (morning) | 1, 2, 5 |
| 4 | 5 | 5 | 5 (morning) | 1, 2, 5, 5 |
| 5 | 9 | 5 | 5 (evening) | 1, 2, 5, 5, 5 |
| 6 | 9 | 6 | 6 (evening) | 1, 2, 5, 5, 5, 6 |
| 7 | 9 | 8 | 8 (evening) | 1, 2, 5, 5, 5, 6, 8 |
The evening list is used up. The 9 left in the morning list goes at the end.
Input: morning = [], evening = [7, 3]
Output: [3, 7]Only the evening list has prices, and it is read from its end.
Input: morning = [4, 4], evening = [4]
Output: [4, 4, 4]Three equal prices are all kept.
0 ≤ length of morning, length of evening ≤ 10^51 ≤ each price ≤ 10^9morning is sorted from small to large, and evening from large to smallInserting every evening price by scanning for its place costs up to 10^5 steps for each of 10^5 prices. That is about 10^10 in all, too slow for 2 seconds.
Both lists are already sorted, so one pass of about 2 x 10^5 steps is enough. A price is at most 10^9, so a 32-bit integer holds it.