Chat app~35 min4s · 256 MBtarget O((n + q) log n) time, O(n log n) spacebit-manipulation · dfs
You work on a chat app. Messages are numbered from 0, and a reply points to the message it answers. A message that starts a thread points to nothing. The app holds many threads, and a thread can be 100,000 replies deep.
Moderators jump through threads. Your team lead asks: "Starting from a message, which message is k replies up, and can the app answer instantly?" The jump length k can be larger than the thread, and there can be 100,000 questions.
Write jump_up(parents, queries).
parents[i] is the message that message i replies to, or -1 when message i starts a thread. Ids are not ordered: a reply can have a smaller id than the message it answers. There are no cycles.queries[k] = [message, k] asks for the message reached by following the reply link k times from message. With k = 0, the answer is message.k steps, the answer is -1.Input: parents = [-1, 0, 1, 2, 2, -1, 5], queries = [[3, 2], [4, 1], [3, 5], [6, 1], [6, 2]]
Output: [1, 2, -1, 5, -1]Messages 0 to 4 form one thread: 0 starts it, 1 replies to 0, 2 replies to 1, and 3 and 4 reply to 2. Messages 5 and 6 form another thread.
| Question | Path from the message | Answer |
|---|---|---|
[3, 2] |
3, 2, 1 | 1 |
[4, 1] |
4, 2 | 2 |
[3, 5] |
3, 2, 1, 0, then nothing | -1 |
[6, 1] |
6, 5 | 5 |
[6, 2] |
6, 5, then nothing | -1 |
Input: parents = [-1], queries = [[0, 0], [0, 1]]
Output: [0, -1]A thread of one message: zero steps stay on it, and one step runs off the top.
Input: parents = [-1, 0, 1], queries = [[2, 0], [1, 0]]
Output: [2, 1]Zero steps up is the message itself.
1 ≤ len(parents) ≤ 100,000, and every entry is -1 or the id of another message.1 ≤ len(queries) ≤ 100,0000 ≤ message < len(parents) and 0 ≤ k ≤ 1,000,000,000.Following the links one by one costs up to 100,000 steps for a deep thread, and 100,000 questions cost 10 billion steps. That is too slow. A jump of k replies can be cut into jumps of 1, 2, 4, 8, ... replies, which takes at most 17 jumps. A value of k above 100,000 cannot stay inside any thread.