Chat app~15 min2s · 256 MBtarget O(n + m) time, O(1) spaceclassic twin: lc-88, lc-21merge-sorted · two-pointers
A chat app keeps each conversation in step across a user's devices. Every message in a conversation has a sequence number, and the numbers only go up. The user's phone and laptop each keep a log of the sequence numbers they received, in increasing order.
Most messages reach both devices, but a device that is offline misses some. After a reconnect, the sync service builds one log for the conversation. It holds every message that reached either device, once, in order. Sequence numbers are large: they reach 10^12.
Write merge_logs(phone, laptop).
phone[i] is the sequence number of a message the phone received. The list is strictly increasing: each number is larger than the one before it.laptop is the laptop's log, in the same form.Input: phone = [2, 3, 5, 8], laptop = [1, 3, 4, 8, 10, 11]
Output: [1, 2, 3, 4, 5, 8, 10, 11]| i | j | phone[i] | laptop[j] | Compared | Taken | merged after the step |
|---|---|---|---|---|---|---|
| 0 | 0 | 2 | 1 | laptop smaller | 1, from the laptop | 1 |
| 0 | 1 | 2 | 3 | phone smaller | 2, from the phone | 1, 2 |
| 1 | 1 | 3 | 3 | equal | 3, once: both pointers move | 1, 2, 3 |
| 2 | 2 | 5 | 4 | laptop smaller | 4, from the laptop | 1, 2, 3, 4 |
| 2 | 3 | 5 | 8 | phone smaller | 5, from the phone | 1, 2, 3, 4, 5 |
| 3 | 3 | 8 | 8 | equal | 8, once: both pointers move | 1, 2, 3, 4, 5, 8 |
| 4 | 4 | none | 10 | the phone ran out | 10 and 11, the laptop's tail | 1, 2, 3, 4, 5, 8, 10, 11 |
Messages 3 and 8 reached both devices, and each appears once. Messages 10 and 11 reached only the laptop, after the phone went offline.
Input: phone = [], laptop = [6, 7, 9]
Output: [6, 7, 9]The phone was off for the whole conversation, so the laptop's log is the answer.
Input: phone = [999999999998, 1000000000000], laptop = [999999999999, 1000000000000]
Output: [999999999998, 999999999999, 1000000000000]These sequence numbers are far beyond the 32-bit limit of 2,147,483,647.
0 ≤ phone.length ≤ 10^5 and 0 ≤ laptop.length ≤ 10^51 ≤ phone[i], laptop[j] ≤ 10^12phone[i] < phone[i + 1] and laptop[j] < laptop[j + 1]Putting both logs together and sorting them is O((n + m) log(n + m)): about 3.5 × 10^6 comparisons when each log holds 10^5 messages. That fits the limit. A sort that moves one value at a time, such as insertion sort, is O((n + m)^2): up to 10^10 steps, far too slow.
Both logs are already sorted, and the problem says so for a reason. With one pointer in each log, you can skip the sort and finish in O(n + m).
Read the values too. Sequence numbers reach 10^12, so they need 64-bit integers: long in Java and long long in C++.