Social feed~40 min4s · 256 MBtarget O((n + q) log n) time, O(n log n) spacebinary-search · dfs
You work on a social feed. Every post is either a new post or a reply to an earlier post. A reply is always newer than the post it answers, so the times fall as you follow the replies back to the start of a chain.
The feed shows the live part of a chain. These are the posts of the chain, from a chosen post back to the start, that were published at or after a cutoff time. Your team lead asks: "How many posts are in the live part of the chain of this post?" The feed can hold 100,000 posts, and chains can be very long.
Write live_chain_lengths(parents, times, queries).
parents[i] is the post that post i replies to, or -1 for a new post. Ids are not ordered. There are no cycles.times[i] is the publication time of post i. For every reply i, times[i] > times[parents[i]].queries[k] = [post, cutoff] asks about the chain that starts at post and follows the replies back to a new post. Count the posts of that chain, including post, whose time is at least cutoff.Input: parents = [-1, 0, 1, 2, 2, -1, 5], times = [1, 5, 9, 12, 20, 3, 8], queries = [[3, 5], [3, 10], [4, 1], [6, 9], [6, 0]]
Output: [3, 1, 4, 0, 2]| Question | Chain from the post, with times | Live posts |
|---|---|---|
[3, 5] |
3 (12), 2 (9), 1 (5), 0 (1) | 12, 9, 5 are at least 5: 3 |
[3, 10] |
3 (12), 2 (9), 1 (5), 0 (1) | 12 only: 1 |
[4, 1] |
4 (20), 2 (9), 1 (5), 0 (1) | all four: 4 |
[6, 9] |
6 (8), 5 (3) | none: 0 |
[6, 0] |
6 (8), 5 (3) | both: 2 |
Input: parents = [-1], times = [4], queries = [[0, 4], [0, 5]]
Output: [1, 0]A time equal to the cutoff is live. A time below it is not.
Input: parents = [-1, 0, 1], times = [0, 1, 2], queries = [[2, 0], [1, 0]]
Output: [3, 2]A cutoff of 0 keeps the whole chain.
1 ≤ len(parents) = len(times) ≤ 100,000, and every entry of parents is -1 or the id of another post.0 ≤ times[i] ≤ 1,000,000,000, and a reply is strictly newer than the post it answers.1 ≤ len(queries) ≤ 100,0000 ≤ post < len(parents) and 0 ≤ cutoff ≤ 1,000,000,000.Walking up a chain costs up to 100,000 steps, and 100,000 questions cost 10 billion steps. That is too slow. The times fall along the chain, so the live posts form a prefix of the path from the post. A prefix can be found with a binary search made of jumps of 1, 2, 4, 8, ... posts, which takes at most 17 jumps.