Search~40 min4s · 256 MBtarget O((n + q) log n) time, O(n + q) spacefenwick-tree
You work on a search app. The app logs, for every step of a long session replay, the id of the document that was opened. Analysts study stretches of the log.
Your team lead asks: "How many different documents were opened between step l and step r?" All the questions are known before you start, and there can be 100,000 of them over a log of 100,000 steps.
Write distinct_in_ranges(items, queries).
items[i] is the id of the document opened at step i.queries[k] = [l, r] asks about the steps l to r, both included.items[l] to items[r].Input: items = [1, 2, 1, 3, 2], queries = [[0, 4], [1, 2], [2, 4], [0, 0]]
Output: [3, 2, 3, 1]| Question | Ids in the stretch | Different ids |
|---|---|---|
[0, 4] |
1, 2, 1, 3, 2 | 3 |
[1, 2] |
2, 1 | 2 |
[2, 4] |
1, 3, 2 | 3 |
[0, 0] |
1 | 1 |
Input: items = [7], queries = [[0, 0]]
Output: [1]One step opens one document.
Input: items = [4, 4, 4, 4], queries = [[0, 3], [1, 2]]
Output: [1, 1]Every step opens the same document, however long the stretch is.
1 ≤ len(items) ≤ 100,0001 ≤ items[i] ≤ 1,000,000,0001 ≤ len(queries) ≤ 100,0000 ≤ l ≤ r < len(items).Collecting the ids of a stretch costs up to 100,000 steps, and 100,000 questions cost 10 billion steps. That is too slow. Because the questions are known in advance, you can answer them in a smart order, and about log n steps for each step and each question is enough.