Search~40 min2s · 256 MBtarget O(n √q) time, O(n + q) spacewindow-counts
A search team keeps a log of the terms users typed, in order. Each entry is a term id. Analysts ask many questions of the form: "In log positions l to r, how many different terms were typed?"
All the questions are known before the answers are needed. A log can have 20,000 entries and 20,000 questions, so scanning each range from scratch is too slow.
Write distinct_in_ranges(terms, ranges).
terms[i] is the term id at log position i.ranges[j] = [l, r] asks about positions l to r, both included. Always 0 ≤ l ≤ r < len(terms).ranges.Input: terms = [1, 2, 1, 3, 2, 1, 4], ranges = [[0, 2], [2, 5], [1, 6], [3, 4]]
Output: [2, 3, 4, 2]The block size is 3. The ranges are answered in the order 0, 1, 2, 3. A window moves from one range to the next, and keeps a count for each term:
| Range | Window moves | Window after | Different terms |
|---|---|---|---|
| [0, 2] | add 1, 2, 1 | positions 0 to 2 | 2 |
| [2, 5] | add 3, 2, 1, then drop 1, 2 | positions 2 to 5 | 3 |
| [1, 6] | add 2, 4 | positions 1 to 6 | 4 |
| [3, 4] | drop 2, 1, 4, 1 | positions 3 to 4 | 2 |
Input: terms = [5, 5, 5], ranges = [[0, 2], [1, 1]]
Output: [1, 1]Every position holds the same term.
Input: terms = [7], ranges = [[0, 0]]
Output: [1]One position, one term.
1 ≤ len(terms) ≤ 20,000, and 0 ≤ terms[i] ≤ 1,000,0001 ≤ len(ranges) ≤ 20,000, and 0 ≤ l ≤ r < len(terms)Scanning each range costs up to 20,000 steps, so 20,000 questions cost up to 400 million steps. That is too slow. The questions overlap a lot, so moving from one range to the next one should cost much less than starting again.