Chat app~12 min2s · 256 MBtarget O(n + q) time, O(n) spacetraversal
A chat app lists a user's conversation threads in a column. The app keeps, for each thread, the number of unread messages. Pressing the "next unread" key jumps to the first thread at or after the thread you are on that has unread messages.
The app handles many presses at once, for example when a user opens the app after a long break. Each press gives the position it starts from. A start past the last thread has no unread thread after it.
Write first_unread(unread, starts).
unread[i] is the number of unread messages of thread i.starts[j] is the thread where press j starts. The press looks at threads starts[j], starts[j] + 1 and so on.unread[i] > 0, or -1 if there is none.starts. A start equal to or larger than unread.length gives -1.Input: unread = [0, 0, 3, 0, 1], starts = [0, 3, 4, 5]
Output: [2, 4, 4, -1]The presses and what they find:
| Press | Start | Threads looked at | First unread thread |
|---|---|---|---|
| 0 | 0 | 0, 1, 2 | 2 |
| 1 | 3 | 3, 4 | 4 |
| 2 | 4 | 4 | 4 |
| 3 | 5 | none: 5 is past the last thread | -1 |
Input: unread = [0, 0, 0], starts = [0, 2]
Output: [-1, -1]No thread has unread messages, so every press answers -1.
Input: unread = [5], starts = [0]
Output: [0]The only thread has unread messages, and the press starts on it.
1 ≤ unread.length ≤ 100,000 (threads)0 ≤ unread[i] ≤ 1,000 (unread messages of one thread)1 ≤ starts.length ≤ 100,000 (presses)0 ≤ starts[j] ≤ 100,000 (start positions)Scanning for every press can cost n steps each. With 100,000 threads and 100,000 presses that is up to 10^10 steps, far beyond the 10^8 a second you can plan with. So answer every press with one lookup, after one pass over the threads.